Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React es6 es2015 modal popup

I'm very new to React and ES6. I'm building a small application using React and I'm following ES6 standard. Now I need to open a modal window on a button click.

I tried react-bootstrap modal and skylight. But did not find much luck.

Can anyone suggest the best way of opening/closing modal along with a callback.

Thanks in advance.

like image 887
Jyo Banerjee Avatar asked Dec 19 '22 02:12

Jyo Banerjee


1 Answers

I've put together an example to illustrate how you might go about this, making use of the parent/child relationship and passing down a callback.

The scenario is basically:

  • There is a parent <App /> component
  • It can show a <Modal /> component
  • <App /> controls whether the <Modal /> is open or not
  • <App /> passes its child, <Modal />, a callback to "closeModal"

See this JSBin example for the full solution in action: http://jsbin.com/cokola/edit?js,output

And a visual summary:

React Modal using Callbacks

<Modal /> is just a "dumb" component. It does not "control" whether it is open or not. This is up to the parent <App />. The parent informs it of how to close itself via passing down a callback this.props.closeModal

class Modal extends React.Component {
  render() {
    const { closeModal } = this.props;

    return (
      <div className="jumbotron" style={{position: 'absolute', width: '100%', top: 0, height: 500}}>
        <h1>Some Modal</h1>
        <button 
          className="btn btn-md btn-primary" 
          onClick={closeModal}
          >Close Modal</button>
      </div>
    )
  }
}

<App /> is aware of the open/closed state and controls its child, <Modal />

class App extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      modalOpen: false
    };
  }

  _openModal() {
    this.setState({modalOpen: true});
  }

  _closeModal() {
    this.setState({modalOpen: false});
  }

  render() {
    const { modalOpen } = this.state;

    return (
      <div>
        <button 
          className="btn btn-md btn-primary" 
          onClick={this._openModal.bind(this)}
          >Open Modal</button>

        {/* Only show Modal when "this.state.modalOpen === true" */}
        {modalOpen 
          ? <Modal closeModal={this._closeModal.bind(this)} />
          : ''}
      </div>
    );
  }
}
like image 95
Erik Aybar Avatar answered Dec 31 '22 02:12

Erik Aybar