dad2131reacthooks
dad2131reacthooks

Reputation: 3

React Hooks: toggle element on map function

See that loop loading two components. I would like to display only <Image /> by default, but when I click this element, I want it to turn into <YouTube /> (only the one I press, the others are still <Image />). I can do this on a class component, but I want to use a hook

export const MusicVideos = () => {
  const [selectedVideo, setVideo] = useState(0);

  return (
    <Wrapper>
          {videos.map(video => (
<div key={video.id}>
             <Image  src={video.image} hover={video.hover} alt="thumbnail" />
            <YouTube link={video.link} />
</div>
          ))}
   </Wrapper/>
  );
};

Upvotes: 0

Views: 1763

Answers (2)

jogesh_pi
jogesh_pi

Reputation: 9782

Create a component like this and pass it to the loop;

const YouTubeToggle = (video) => {

    const [selectedVideo, setVideo] = useState(0);

    return (
        <div key={video.id}>
            {selectedVideo == 0 &&
                <Image  src={video.image} onClick={() => setVideo(!selectedVideo)} hover={video.hover} alt="thumbnail" />
            }
            {selectedVideo != 0 &&
                <YouTube link={video.link} />
            }
        </div>
    );
}

export const MusicVideos = () => {
  const [selectedVideo, setVideo] = useState(0);

  return (
    <Wrapper>
          {videos.map(video => (
            <YouTubeToggle video={video} />
          ))}
   </Wrapper/>
  );
};

Upvotes: 0

Amit Chauhan
Amit Chauhan

Reputation: 6869

you can bind onClick for your image and setVideo to video.id and compare with video.id to render image or video.

export const MusicVideos = () => {
  const [selectedVideo, setVideo] = useState(0);

  return (
    <Wrapper>
          {videos.map(video => (
            {selectedVideo !== video.id ?
             <Image onClick={() => setVideo(video.id)  src={video.image} hover={video.hover} alt="thumbnail" /> :
             <YouTube link={video.link} />
          ))}
   </Wrapper/>
  );
};

Upvotes: 1

Related Questions