0

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/>
  );
};
1
  • 1
    videos.map((video, index) => { return (<>{selectedVideo === index ? <image onClick={() => setVideo(index)}/> : <youtube/> </>) } Commented Jan 16, 2020 at 12:19

2 Answers 2

1

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/>
  );
};
Sign up to request clarification or add additional context in comments.

Comments

0

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/>
  );
};

1 Comment

why are you using 0 instead of false?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.