N
N
nivaech2019-06-21 08:33:20
JavaScript
nivaech, 2019-06-21 08:33:20

How to change array element on click?

There is an array with photos, which is rendered using map:

<div className="about-pictures-container">
                { images.map(image => {
                  return (
                    <ImageCard
                    key = {person.id}
                    name = {eng ? person.nameENG : person.nameRU}
                    image = {person.img}
                    bio = {eng ? person.bioENG : person.bioRU}
                    />
                  )
                }) }
              </div>

This is what the image component looks like.
<div className="image-card">
                            <div className="card-image-info-container">
                                <img className={"bio-img " + (showBio ? "invisible" : null)} src={image} onClick={toggleBio} />
                                <div className={"bio-text-container " + (showBio ? "bio-visible" : null)}>
                                    <p className="card-bio"> {bio} </p>
                                    <button className="btn bio-btn" onClick={() => toggleBio(id)}>Close</button>
                                </div>
                            </div>       
                            <p className="image-card-name"> {name} </p>
                        </div>

I'm trying to make it so that when you click on a photo, the picture disappears, and a biography of a person appears in its place. This function is responsible for this:
toggleBio = id => {
      this.setState({
        showBio: ! this.state.showBio
      })
    }

The function works clumsily, because on click it changes the state of absolutely all elements. I know that you need to check the id on click, but I still don’t fully understand how to do it.
How can I change the state of only the element that the user clicked on?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-06-21
@nivaech

You can simply change the state of the card:

const ImageCard = ({ image, bio }) => {
  const [showBio, setShowBio] = useState(false);
  const handler = useCallback(() => {
    setShowBio(state => !state);
  }, []);

  return (
    <Wrapper>
      {showBio ? <Bio bio={bio} /> : <Image src={image} />}
      <Button onClick={hanlder}>Show bio</Button>;
    </Wrapper>
  );
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question