Modals are separate windows within an application, most often as a dialog box. They are a common user interface pattern for providing information or requiring confirmation.
In this tutorial you will learn about how to implement a modal component in your React project. You’ll create a Dashboard
component to manage state and a button to access the modal. You’ll also develop a Modal
component to build a modal and a button to close. Your project will display and close a modal upon clicking a button.
To complete this tutorial, you will need:
Dashboard
ComponentThe dashboard is where you will display your modal. To begin your dashboard, import an instance of React and the Component
object into your Dashboard.js
file. Declare a Dashboard
component and set your state:
import React, { Component } from "react";
class Dashboard extends Component {
constructor() {
super();
this.state = {
show: false
};
this.showModal = this.showModal.bind(this);
this.hideModal = this.hideModal.bind(this);
}
showModal = () => {
this.setState({ show: true });
};
hideModal = () => {
this.setState({ show: false });
};
}
export default Dashboard
Your state includes the property show
with the value of false
. This allows you to hide the modal until a user prompts it to open. The functions showModal()
updates your state with the .setState()
method to change the value of your show
property to true
when a user opens the modal. Likewise, the .setState()
method in your hideModal()
function will close the modal and change the value in your show
property to false
.
Note: Remember to bind your functions on the constructor()
using the .bind()
method.
Once you’ve applied your state and functions, your render()
lifecycle method will handle displaying your modal within the return()
statement:
import React, { Component } from "react";
class Dashboard extends Component {
// ...
render() {
return (
<main>
<h1>React Modal</h1>
<button type="button" onClick={this.showModal}>
Open
</button>
</main>
);
}
}
export default Dashboard
The button
accepts the React JSX attribute onClick
to apply the .showModal()
function and open your modal. You will export your Dashboard
component to a higher-order App
component connected to your root HTML file.
Modal
ComponentCreate a new file, Modal.js
and declare a stateless functional Modal
component with three arguments, handleClose
, show
, and children
. The argument show
represents the show
property on your state:
import './modal.css';
const Modal = ({ handleClose, show, children }) => {
const showHideClassName = show ? "modal display-block" : "modal display-none";
return (
<div className={showHideClassName}>
<section className="modal-main">
{children}
<button type="button" onClick={handleClose}>
Close
</button>
</section>
</div>
);
};
Your return()
statement passes the argument children
, represented as props.children
, is a reference to the functionality of opening and closing the modal. The modal also contains a button with a the React JSX onClick
attribute that accepts the hideModal()
method, here represented as the argument handleClose
, passed as props into your Dashboard
component.
The variable showHideClassName
assigns its value a conditional to check if the value of the show
property in your state is true
. If so, the modal will appear. Else, the modal will hide. The properties display-block
and display-none
to show and hide the modal are handled through the modal.css
file imported into your Modal
component.
Start a new file, modal.css
, and set the rules to style the size, color, and shape of your Modal
:
.modal {
position: fixed;
top: 0;
left: 0;
width:100%;
height: 100%;
background: rgba(0, 0, 0, 0.6);
}
.modal-main {
position:fixed;
background: white;
width: 80%;
height: auto;
top:50%;
left:50%;
transform: translate(-50%,-50%);
}
.display-block {
display: block;
}
.display-none {
display: none;
}
This will produce a centered modal with a white box outline and a shaded background. With your Modal
component complete, let’s integrate your component into your Dashboard
.
Modal
ComponentTo combine your Modal
into your Dashboard
, navigate to your Dashboard.js
file and import your Modal
component below your React insantiation:
import React, { Component } from "react";
import Modal from './Modal.js';
class Dashboard extends Component {
// ...
render() {
return (
<main>
<h1>React Modal</h1>
<Modal show={this.state.show} handleClose={this.hideModal}>
<p>Modal</p>
</Modal>
<button type="button" onClick={this.showModal}>
Open
</button>
</main>
);
}
}
export default Dashboard
In your return()
statement, include your Modal
component to display and hide the modal. The attributes show
and handleClose
are props from your Modal
component to manage the logic of your state and the hideModal()
function.
Your Dashboard
and Modal
components will now render on your browser:
Observe how your new Modal
component now opens and close.
In this tutorial, you learned how React can be used to implement modals by passing props and functionality from one component to another.
To view this project live, here is a CodePen demo of this project.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
It works, easier than using ReactDOM.createPortal, thank you!
Anywhere in the window whenever I clicked, Modal should disappear! How?
please i want to create different modals on one page using this method but its not working its showing only the last modal that i created
If anyone is getting the error : Failed to compile.
./src/App.js Attempted import error: ‘Modal’ is not exported from ‘./Modal.js’.
it is because you need to do two things.
2 change the import statement of Dashboard.js it be: import {Modal} from ‘./Modal.js’;
How can I prevent the page underneath the modal from scrolling while the modal is present?