How to Create a Modal in a React App?

Sometimes, we want to add a modal into our React app.

In this article, we’ll look at how to add a modal into our React app.

Create a React Modal

We can use React’s portal feature to render our component anywhere.

This way, we can create a modal that’s attached to whatever element we want.

For instance, we can write:

const ModalComponent = ({ children, onClose }) => {
  return createPortal(
    <div className="modal" onClick={onClose}>
      {children}
    </div>,
    document.getElementById("portal")
  );
};

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

    this.state = {
      showModal: false
    };
  }

  render() {
    return (
      <div>
        <button onClick={() => this.setState({ showModal: true })}>
          Open modal
        </button>
        {this.state.modalOpen && (
          <ModalComponent onClose={() => this.setState({ showModal: false })}>
            <h1>modal content</h1>
          </ModalComponent>
        )}
      </div>
    );
  }
}

We create a ModalComponent component to let us nest content inside it.

We can do that since it takes the children component.

All we have to do is render the children prop.

We use React’s createPortal method to let us render the div anywhere we want.

In App , we created a button to let us open the modal.

To do that, we set the showModal state to true .

We also created a function that we pass into the onClose prop of ModalComponent so that showModal can be set to false .

This will close the modal since ModalComponent is only shown when showModal is true .

Conclusion

We can use React’s portal feature to render our component anywhere.