How to Pass data, Open React-Modal from Parent Functional Component

This example tutorial will teach how to open the React Modal component in the child functional component. We will handle the OpenState of Modal from the parent component and pass dynamic data from parent to child. Moreover, the react-modal component will pass back data to the parent after the modal is closed.

The react-modal package module provides use reusable components to create modals very easily and quickly in a react application. We can easily add our own style and animation to the modal container. it provides a good number of event handlers to control data flow from/ to modal components.

In this tutorial, we will create a separate modal component named MyModalComponent, that will be abstracted as a component, but the event handlers including open, after-open, after-close will be watched by the parent component(App.js)

How to Pass Data and Open Modal from Parent Function Component?

Let’s walk through quick steps to implement Modal in react application:

Installation

First, install the react-modal package module in your React application.

npm install react-modal

Create Modal Component

Now, we will create a new custom function component at ~src/mymodal.component.ts file. Update the file with the following code:

import React from 'react';
import Modal from 'react-modal';

const customStyles = {
  content: {
    top: '50%',
    left: '50%',
    right: 'auto',
    width: '70%',
    bottom: 'auto',
    marginRight: '-50%',
    transform: 'translate(-50%, -50%)'
  }
};

function MyModalComponent(props) {
  function afterOpenModal(e) {
    props.onAfterOpen(e, 'After Modal Opened');
  }

  function onModalClose(event) {
    let data = { name: 'example', type: 'closed from child' };
    props.onCloseModal(event, data);
  }

  return (
    <div>
      <Modal
        isOpen={props.IsModalOpened}
        onAfterOpen={e => afterOpenModal(e)}
        style={customStyles}
        ariaHideApp={false}
      >
        <h2>{props.dynData.title}</h2>
        <button onClick={e => onModalClose(e)}>close</button>
        <div>
          <ul>
            {props.dynData.body.map(fr => (
              <li>{fr}</li>
            ))}
          </ul>
        </div>
      </Modal>
    </div>
  );
}

export default MyModalComponent;

The props play an important role here in our MyModalComponent functional react component. It is used to get property values from the parent component.

The <Modal/> component is having the following dynamic events and data coming to the child Modal component from the parent App component.

  • Title & Body data: The dynData prop is providing the title and body list to update the Modal content.
  • isOpen: The isOpen prop controls the visibility of Modal, which is controlled by parent props boolean value.
  • onAfterOpen: This event is triggered after the Modal is opened. This in turn is calling the local afterOpenModal function which is passing back the onAfterOpen callback function.
  • onModalClose: The event called to close the modal by triggering the onCloseModal props function.

Using Modal Component in Parent App.js

Next, open the App.js file, which is a parent component in our example application. Update it with following code:

import React from 'react';
import './style.css';
import MyModalComponent from './mymodal.component';

export default function App() {
  const modalData = {
    title: 'My Title From Parent',
    body: ['Apple', 'Ipple', 'Opple', 'Upple', 'Epple']
  };
  const [modalIsOpen, setIsOpen] = React.useState(false);

  function openFromParent() {
    setIsOpen(true);
  }

  function handleCloseModal(event, data) {
    console.log(event, data);
    setIsOpen(false);
  }

  function handleAfterOpen(event, data) {
    console.log(event, data);
  }

  return (
    <div>
      <h1>
        React-Modal Example - Pass Data and Open from Parent Functional
        Component
      </h1>

      <MyModalComponent
        dynData={modalData}
        IsModalOpened={modalIsOpen}
        onCloseModal={handleCloseModal}
        onAfterOpen={handleAfterOpen}
      />
      <button onClick={openFromParent}>Open Modal</button>

      <p>
        <a href="" target="_blank">
          Complete Tutorial
        </a>
      </p>
    </div>
  );
}

The MyModalComponent component is imported and has the following props which are getting passed to the child component with Modal.

  • dynData: This contains the data object with title and body array item list. This can be the remote API data as well.
  • IsModalOpened: This prop is passing the boolean to control the Modal visibility from a parent.
  • onCloseModal: Event handler to get triggered after Modal is closed. This callback event handler will return any data which is returned back by the Modal component.
  • onAfterOpen: Event handler triggered after modal is opened successfully.

 

You can check the working example on StackBlitz.

 

Summarizing

We discussed the dynamic implementation of react-modal taking care of the real-world application use-cases. You can check the working example on StackBlitz and modify the existing codebase according to your needs.

The Modal is getting props from the parent and controlling its callback events completely from the parent by passing data to Modal and back to the parent after it is closed.

You can share your feedback or further enhancement, requirements .. thanks

Leave a Comment

Your email address will not be published. Required fields are marked *