DEV Community

loizenai
loizenai

Posted on

React Modal example

https://grokonez.com/frontend/react/react-modal-example

React Modal example

In this tutorial, we're gonna add a React Modal to Note Application. It appears every time we click on a Note item.

Related post: Build & run React Application with Webpack – React Webpack example

More practice: Style React Application – apply SCSS/CSS files to React with Webpack

Goal

When clicking on any Note item, a new Box that displays item content is opened. We can close by OK button, by clicking on outside area, or by pressing ESC key.

react-modal-example

How to

Install React Modal

We can use npm or yarn:


npm install react-modal
yarn add react-modal

Or add dependency in package.json:


{
  "name": "add-modal",
  "version": "1.0.0",
  "main": "index.js",
  "author": "JavaSampleApproach",
  "scripts": {
    ...
  },
  "dependencies": {
    ...
    "react-modal": "3.3.2",
    ...
  }
}

Then run cmd yarn install.

Create React Modal Component

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

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

const NoteModal = (props) => (
    <Modal
        isOpen={!!props.selectedNote}
        onRequestClose={props.closeNoteModal}
        style={modalStyles}
        contentLabel='Selected Note'
        ariaHideApp={false}
    >
        <h4>Selected Note</h4>
        <p>{props.selectedNote}</p>
        <button onClick={props.closeNoteModal}>OK</button>
    </Modal>
);

export default NoteModal;
  • isOpen indicates that the modal should be shown (true) or not (false).
  • onRequestClose: function runs when the modal is requested to be closed (clicking on overlay or pressing ESC).
  • style: styles to be used.
  • ariaHideApp: describes if the appElement should be hidden (true) or not (false).

    Add React Modal to parent Component

More at:

https://grokonez.com/frontend/react/react-modal-example

React Modal example

Top comments (0)