Search code examples
reactjsreact-modal

Set State with the right data in React Modal


I have a loop in my project that displays all the items that exist in my Firebase database. I use Lodash and a renderPosts method for that, like you can see in this following code:

   renderPosts() {
    const { open } = this.state;
    this.removeToCollection = this.removeToCollection.bind(this);
    return _.map(this.state.cotations, (cotations, key) => {
      return (
        <div className="item col-md-12" key={key} id={key}>
            <h3>{cotations.nom}</h3>
            <p>Contenu: {cotations.content}</p>

            <button className="btn btn-danger" onClick={(e) => {if(window.confirm('Voulez vous vraiment supprimer cette capsule du catalogue ?')){this.removeToCollection(key, e)};}}>Supprimer</button>
            <button className="btn btn-warning" onClick={this.onOpenModal}>Modify</button>


            <Modal open={open} onClose={this.onCloseModal} center>
              <h2>{cotations.nom}</h2>
              <form>
              <p>Nom du document:<input type="text" class="form-control" name="nom"  value={this.state.nom} onChange={this.onInputChange}></input></p>
              <CKEditor
                    editor={ ClassicEditor }
                    data= {this.state.content}
                    onChange={this.handleEditorChange()}
                />

              <button className="btn btn-success" onClick={this.updateContent}>Update</button>
              </form>
            </Modal>
        </div>
      )
    })
  }

Also, I wish that when the user clicks on the modify button, a modal opens with the possibility of modifying the item. For this I use "React-Responsive-Modal" and the following code:

  onOpenModal = () => {
    this.setState({ open: true, nom: '???' , content: '???', });
  };

  onCloseModal = () => {
    this.setState({ open: false });
  };

To retrieve in my modal the information of the item that I have to modify, I have to pass them in my "onOpenModal" function, to update my State. But I can not pass the information. I tried everything I could imagine but I can not find. Do you have an idea ?

Thank you in advance


Solution

  • Just call the onOpenModal in an anonymous function and pass the required values as arguments to openModal

    <button className="btn btn-warning" onClick={()=>{ this.onOpenModal(cotations.nom,cotations.content) }}>Modify</button>
    

    and change openModal to consume these arguments

     onOpenModal = (nom,content) => {
       this.setState({ open: true, nom: nom, content: content, });
    
       //or this if you want to use ES6 concise properties
       //this.setState({ open: true, nom, content });
     };
    

    Hope this helps !