0

In a React project, I have JSON data as follows

const data = [
  { id: '123abc', comment: 'How are you?' },
  { id: '234abc', comment: 'https://flower.jpg' },
  { id: '123xyz', comment: 'Whatsupp?' },
  { id: '335sde', comment: 'https://galaxy.png' },
];

I'am trying as under

<div>
{/* For images */}
<img src={data.comment} height="50px"/>

{/* For text */}
<Typography variant="caption">
   {data.comment}
</Typography>
</div>

As seen above some comments are text whereas some are images. So, how to render it? Any appropriate solution highly appreciated

aitchkhan
  • 1,842
  • 1
  • 18
  • 38
Prakash Patil
  • 247
  • 2
  • 11

2 Answers2

3

create function for check URL and use conditional rendering.

validateUrl = (string) => {
    var res = string.match(
      /(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g
    );
    return res !== null;
  };
  render() {
    return (
      <div>
        {this.validateUrl(data.comment) ? (
          <img src={"data.comment} height="50px" />
        ) : (
          <Typography variant="caption">{data.comment}</Typography>
        )}
        
        {/* // for comment:"How are you?" it returns false and it renders text and
        for comment:"https://galaxy.png" it returns true and it renders image */}
      </div>
    );
  }
Deep Patel
  • 70
  • 7
  • 2
    fwiw, I would advise to create the desired function outside of `render` method. otherwise each rerender `validateUrl` is recreated. – buzatto Feb 15 '21 at 05:54
0

This should work:

const data = [
  { id: '123abc', comment: 'How are you?' },
  { id: '234abc', comment: 'https://flower.jpg' },
  { id: '123xyz', comment: 'Whatsupp?' },
  { id: '335sde', comment: 'https://galaxy.png' },
];

const validateUrl = (string) => {
  const result = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g)
  return result !== null;
}

const renderImage = (link) => (<img src={link} height="50px"/>)
const renderTypography = (comment) => (
  <Typography variant="caption">
    {comment}
  </Typography>
);

render () {
  return data.map(row => (
    <div>
      validateUrl(row.comment) ? renderImage(row.comment) : renderTypography(row.comment)
    </div>
  ))

}

aitchkhan
  • 1,842
  • 1
  • 18
  • 38