Search code examples
reactjsreact-modal

How to pass VideoId from a list to React Modal Video


I am trying to play youtube video in a modal window on button click in my react app. I am using "react-modal-window" node module for the modal. I am getting an array of youtube video Ids and passing the ids to modal in the following way but only the last id from the array is taken by the modal window. However if I try to print the video id, am getting respective ids. Can any one please help in fixing this?

<tr>
    <th></th>
    {filteredProductVideoId.map(k => 
        <td key={k}>VideoID: {k}
            <ModalVideo channel='youtube' isOpen={this.state.isOpen} videoId={k} 
            onClose={() => this.setState({isOpen: false})} />
            <button onClick={this.openModal}>Watch Video</button>
        </td>)
    }
</tr>

To view the output, please click this link -https://7jrz33j35x.codesandbox.io/ Select all four products and click compare button. A tabular view of comparison displays. In the last row there is a "watch video" button for each product. Beside the button, respective id got displayed(for debugging purpose) but on clicking watch video, the video with last id from the array is played


Solution

  • pass the clicked button video id via state.. like below

    this.state = {
      //use this props inside modal video view
      currentVideoId : null 
    }
    
    this.updateVideoId(currentVideoId){
      this.setState({currentVideoId})
    }
    
    //your jsx change button onClick like below
    <tr>
        <th></th>
        {filteredProductVideoId.map(k => 
            <td key={k}>VideoID: {k}
                <ModalVideo channel='youtube' isOpen={this.state.isOpen} videoId={k} 
                onClose={() => this.setState({isOpen: false})} />
                <button onClick={()=>{this.updateVideoId(k)}}>Watch Video</button>
            </td>)
        }
    </tr>