Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

opening a modal with the click of a button

The next code uses a Modal react component:

export class AddWorkLogEditor extends React.Component {
    constructor(props) {
        super(props);

        this.addWorkLog = this.addWorkLog.bind(this);       
        this.onOpenModal = this.onOpenModal.bind(this);
        this.onCloseModal = this.onCloseModal.bind(this);
        this.state = {
             open:true

           };
      }

  onOpenModal() {
     this.setState({open: this.props.openModal});
  }

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

  addWorkLog() {

   }



 render() {
      const bstyle = {
         backgroundColor: 'green',
         textAlign:"left",
         paddingLeft: '0px',
         color: 'white'
    };
 const {open} = this.state;
       return (
           <div>
                <Modal open={open} onClose={this.onCloseModal} little>
                <h3>hi gi</h3>

                 <Button bsStyle="success" bsSize="small" onClick ={(ev) => {console.log(ev)} }> Save </Button>
                 </Modal>
            </div>
       );
    }
}

I am trying to call it using:

addWorkLog()
{
      return <AddWorkLogEditor/>;
}

and

 createAddWorkLogButton () {

    return (
        <button style={ { color: '#007a86'} } onClick={this.addWorkLog} >Add Work Log</button>
    );
 }

I mean, after I click at this button nothing shows up. Is there another way to call that modal? I am importing the modal from:

import Modal from 'react-responsive-modal'

like image 975
Jose Cabrera Zuniga Avatar asked Jul 07 '17 20:07

Jose Cabrera Zuniga


1 Answers

You are trying to render the modal only once the button is clicked, while that's quite natural for non-react environments, in react it works in a different way. In the simplest solution the Modal should be always rendered, and when a user clicks the button you change the modal open property to true.

{ /* all the markup of your page */ }
<button onClick={() => this.setState({showModal: true})}>Add Work Log</button>
{ /* anything else */ }

{ /* modal is here but it is hidden */ }
<Modal open={this.state.showModal}>...</Modal>

Alternatively, you can just skip the modal rendering at all until the showModal becomes true.

this.state.showModal && <Modal open>...</Modal>
like image 75
Dmitry Sokurenko Avatar answered Sep 27 '22 17:09

Dmitry Sokurenko