DEV Community

loizenai
loizenai

Posted on

1

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay