Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS Modal opening multiple times when in a Loop

Hi I am playing around with ReactJS, and found this awesome Modal Component to open Videoes in a Modal, but when I put the Modal inside a loop with multiple links and open the modal, it open like 5 times if I have 5 links. What do I do wrong?

Modal Component: https://github.com/appleple/react-modal-video

import React from 'react'
import ReactDOM from 'react-dom'enter code here
import ModalVideo from 'react-modal-video'

class App extends React.Component {
 constructor () {
    super()
    this.state = {
      isOpen: false
    }
    this.openModal = this.openModal.bind(this)
  }

  openModal () {
    this.setState({isOpen: true})
  }

      render () {
        return (
          <div>
            <ModalVideo channel='youtube' isOpen={this.state.isOpen} videoId='L61p2uyiMSo' />
            <button onClick={this.openModal}>Open</button>
          </div>
        )
      }
    }

    ReactDOM.render(
      <App />,
        document.getElementById('root')
    )

My Loop with the Modal Component Inside:

render(){
    return(
            <div>
                {(this.props.frag.all == null) ? null :
                  this.props.frag.all.map((frags, i) => {
                  return (
                  <li key={frags.id} className="group" id="" style={{width: 'calc(13% - 30px)'}}>
                    <ModalVideo channel='youtube' isOpen={this.state.isOpen} videoId='{frags.url}' />
                      <button onClick= {this.openModal.bind(this)}>Open</button>
                  </li>
                )})
              }
          </div>
like image 577
DbTheChain Avatar asked Aug 08 '26 06:08

DbTheChain


1 Answers

The problem is that each ModalComponent uses the same state property isOpen so when you click on any link it sets this property and each ModalComponent becomes open. You should use unique property for each modal (you can use poperty which you already uses as key).

<li key={frags.id} className="group" id="" style={{width: 'calc(13% - 30px)'}}>
    <ModalVideo channel='youtube' isOpen={this.state.isOpen[frags.id]} videoId='{frags.url}' />
    <button onClick= {this.openModal.bind(this, frags.id)}>Open</button>
 </li>

And your method:

 openModal (id) {
    this.setState({
       isOpen: {
          [id]: true
       }
    });
 }
like image 135
Bartek Fryzowicz Avatar answered Aug 09 '26 18:08

Bartek Fryzowicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!