Open modal click with a button

The following code uses a react modal 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>
    );
 }

      

What I mean is that after I click on this button, nothing appears. Is there any other way to call this modal? I am importing a modal from:

import modal from react-react-modal

+3


source to share


1 answer


You are trying to make the modal only after the button is pressed, while this is quite natural for non-reactive environments, it works differently in reactive. In the simplest solution, you Modal

should always display, and when the user clicks on the button you change the modal property open

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 modal rendering at all until showModal

true.

this.state.showModal && <Modal open>...</Modal>

      

+5


source







All Articles