Render image conditionally

Hello awesome devs, i am working with this fake data (an array of 2 objects) in my react app project. One of image key in the objects doesn’t have a value. After mapping through the array of data, an image, a button are displayed.

What I want to achieve is to set the image for the first object to (https://images.unsplash.com/photo-1511044568932-338cba0ad803?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80) when it’s button is clicked:

const catsArr = [
{
id: 1,
image: ' ',
name: 'cat 1',
},
{
id: 2,
image: 'https://images.unsplash.com/photo-1533738363-b7f9aef128ce?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1035&q=80 ',
name: 'cat 2',
},
]

const Cats = () => {
return (
{catsArr.map((cat) => {
return <div key={cat.id}>
<img src={cat.img} alt={cat.name}/>
<button>{cat.name}</button>
</div>
}
)}
)
}

export default Cats

Hi,

You can do it like this:

import { useState } from 'react';

const Cats = () => {
  const catsArr = [
    {
      id: 1,
      img: '',
      name: 'cat 1',
    },
    {
      id: 2,
      img: 'https://images.unsplash.com/photo-1533738363-b7f9aef128ce?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1035&q=80 ',
      name: 'cat 2',
    },
  ];

  const [cats, setCats] = useState(catsArr);
  
  const handleClick = (cat) => {
    if (cat.id !== 1) return
    
    setCats(currentCats => {
      currentCats[0].img = 'https://images.unsplash.com/photo-1511044568932-338cba0ad803?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80';
      return [...currentCats];
    });
  }

  return (
    cats.map((cat) => {
      return (
        <div key={cat.id}>
          <img src={cat.img} alt={cat.name} />
          <button onClick={() => handleClick(cat)}>{cat.name}</button>
        </div>
      );
    })
  );
}

export default Cats

Is that the kind of thing you are after?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.