React bootstrap modal in class component

React bootstrap modal in class component

Posted by Ervin Adams on June 8, 2022

React bootstrap modal in class component

React bootstrap modal in class component

Posted by Ervin Adams on June 8, 2022

Sometime you may need a quick and easy way to display data in a dialogue box in your React project. Here is how a boostrap modal work in a class component.

Step 1. Install react boostrap package.

npm install react-bootstrap

Step 2 Create a component called AppModal.js

You can place AppModal.js file in a partial or util directory

Once your done copy code below to render method:

<Modal
    show={this.props.isOpen}
    onHide={this.props.closeModal}>

    <Modal.Header>
        <h5>Modal title</h5>
    </Modal.Header>
    <Modal.Body>
        <div>Modal body text goes here.</div>
    </Modal.Body>
    <Modal.Footer>
        <Button variant="secondary" onClick={this.props.closeModal}>
            Close
        </Button>
        <Button variant="primary" onClick={this.props.closeModal}>
            Save Changes
        </Button>
    </Modal.Footer>
</Modal>

The code snippet above uses the modal from react-boostrap, it consist of the following:

  • A header, a body and a footer section to store contents
  • Show attribute containing a prop called isOpen. The prop is used to show the modal.
  • onHide attribute containing a prop called closeModal. The prop is used to hide the modal

The closeModal prop is also placed in the bottons within the the footer of the modal.

Step 3. Add the AppModal component where ever you plan to use it.

In this instance AppModal will be used in App.js, here is how it looks:

 

class App extends Component{
    constructor(props) {
        super(props);

        this.state = {
            showModal: false,
        };
    }

    openModal = () => this.setState({ showModal: true });

    closeModal = () => this.setState({ showModal: false});

    render() {
      return (
          <div className="container">
              <div className="mx-auto col-6 mt-5">
                  <button type="button" onClick={this.openModal} className="btn btn-primary">show modal</button>
                  <AppModal closeModal={this.closeModal} isOpen={this.state.showModal}/>
              </div>
          </div>
      );
    }
}

export default App;

So, in the above snippet there are 2 methods openModal and closeModal. The openModal is placed in a onClick event located within a button

The AppModal component consist of 2 props, one is the showModal state which switches to true on button click within the App component. 

The other is the closeModal method which switches the showModal state to false on button click within the footer of the Modal.

Once you click on the button in the App component, the Modal should pop up.

Happy coding!