Harvir
Harvir

Reputation: 131

ReactJs App's mapped list of buttons from Json file only have the last value of json array

I am making list of button that will lead to different YouTube videos on ReactJs page. The issue is that when I map the links from json file (which contains video links), all the buttons get the last link of the mapped array. I need a way that all the rendered buttons will get their respective links. My code is below, I am using react ModalVideo to show my YouTube video.

    <ul className="list-unstyled">
         {datalist.lectures.map((value, index) => { 
                return  (
          <li key={index}>
          <ModalVideo channel='youtube' autoplay isOpen={isOpen} videoId={value} onClose={() => setOpen(false)} />
          
          <button className="play-icon" onClick={()=> setOpen(true)}> <i className="las la-play"></i> Lecture: {index+1}</button>
          </li>
                         )})}
          </ul>

All the links are coming from Json file where the code looks like this

 "lectures": [
                "BT4YihNXiYw",
                "NSFLhnv2pQI",
                "sEPxqpFZit8",
                "fU8QhoUJ_sE",
                "r3XFYOtvUng",
                "MZAkMddxhpg"
                 ]

I think the problem I have right now is that after the page render and mapping ends it only remembers what the last link is store in value, because of that no matter which button i click it shows me the last value of the mapped array

Upvotes: 1

Views: 203

Answers (1)

ChinKang
ChinKang

Reputation: 4342

Just some quick ideas looking at the minimal snippets available.

  1. let's not to render multiple ModalVideo component like above, move it out from the map.
  2. Use another state to keep track the change of the youtube videos' ID.

For example

const [isOpen, setOpen] = useState(false);
const [videoId, setVideoId] = useState(null);
const playVideo = (vid) => {
    setOpen(true);
    setVideoId(vid);
};

return (
    <div>
        <ModalVideo
            channel='youtube'
            autoplay
            isOpen={isOpen}
            videoId={videoId}
            onClose={() => setOpen(false)}
        />
        <ul className="list-unstyled">
            {
                datalist.lectures.map((value, index) => {
                    return (
                        <li key={index}>
                            <button className="play-icon" onClick={() => playVideo(value)}>
                                <i className="las la-play"></i>
                                Lecture: {index + 1}
                            </button>
                        </li>
                    )
                })
            }
        </ul>
    </div>
);

Upvotes: 1

Related Questions