How To Implement a Modal Component In React

July 12, 2023
How to Implement a Modal Component in React



Want to add a dialog box to your website or application? Use React Modals. An integral UI element, they open as a separate box and are used to request or deliver information. Thanks to the state hook and the context API, implementing modal components in React is now pretty simple.

react dev jobs

So, without further ado, let’s cut right to the chase and discuss how to implement a React modal component.

How to Implement React Modal Component

Implementing modal components in React is a three-step process beginning with dashboard creation and ending at modal component incorporation.

Step 01 – Creating the Dashboard Component

A modal in React displays in the dashboard. First, import a React instance and a component object from React into the Dashboard.js file.

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

In the above, the property show set to false hides the modal until the user prompts it to  open. While the function showModal(), using the .setState() method, updates its status to true. Similarly, the hideModal() closes the modal by changing its value back to false.

Next, the render() lifecycle method will begin work and display the defined React Modal below 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

In the above, the button under React Modal links the attribute onClick to trigger the .showModal() function and change its status from false to true. Next, export the Dashboard to a higher-order component linked to the root HTML file.

Step 02 – Constructing the Modal Component

The next step is to create a Modal.js file & declare a Modal component, a stateless function. It must have three arguments show, handleClose, and children.

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>

  );

};

In the above, the return() passes props.children, which deals with triggering the React modal component to open or close. In addition, the React modal has a button onClick that queues the hideModal() method. Denoted as handleClose, it moves to the Dashboard component as a prop.

Then, the next part of building React modal component is defining size, color, shape, and other style elements. For this, start a new file and set the rules.

.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;

}

The above code creates a centered React modal with a shaded backdrop and a white outline. Component ready? Now let’s implement it into the Dashboard.

Step 03 – Integrating the Modal Component

Integrating the React modal component into the Dashboard is simple. All you need to do is navigate to the previously-created Dashboard.js file and import.

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

Remember, it is a must to include the Modal component in the return() to make it show or hide effortlessly. Both attributes handleClose and show, function as a prop to manage the logic of the state component.

Conclusion

Now you know how to implement React modal to power up your website user interface with dialog boxes and the likes to request or deliver information to the user. Such UI elements bring your web application to life, make it more responsive, and enhance the user experience.

In this article, you explored a three-step process to implement React modal components in React with syntax examples. Use the codes to build and integrate your personalized React modals in your React applications.

Also Read: All You Need To Know About Working With React Suspense

react jobs



author

admin


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US