Reusable Modal in React

Reusable Modal in React

Problem Description:

I have data

const data  = [
         id: "React",
        img: "",
       info: "React is the most popular JavaScript library and is used by Facebook, Instagram, Netflix, Airbnb, Uber Eats, and many more.",
       data: [{"React Hooks": {
        description: "React Hooks is a new addition in React 16.8. It 
       lets you use state and other React features without writing a 
      {"React Redux": {
        description: "React Redux is the official React binding for 
        Redux. It lets your React components read data from a Redux 
        store, and dispatch actions to the store to update data."}

I also have buttons with set name and id similar to data.[0].id. I would like to click button and display modal corresponding to button.


  1. How do I get Modal component to extract this data according to button/element clicked? //I suspect an API call, or maybe props.

  2. Shall I add multiple modal components underneath each button? // I am thinking yes.

  3. Where can I find out more on this topic? // I have been at it for
    hours and a right direction would be great.

Further clarification zone:

import Modal from './Modal'

export function App() {
  const [isOpen, setIsOpen] = useState(true)

  return (
    <button id={React}>
      <Modal open={isOpen}/>

    <button id={Express}>
      <Modal open={isOpen}/>

Modal Component

Import data from './data.js'

export default Modal({open}) {
  if(!open) return null

  return (
   <div className='overlay'>
     <div className='modalContainer'></div>

Solution – 1

You can use react-modal library by installing it as

npm i react-modal

into your React project and use it like:

import Modal from "react-modal";

If you want to have multiple buttons, you can use your data array and map through it like

{, index) => (
            onClick={() => {

By doing so you are setting also pattern to which index you want. You can then show the modal depending on which pattern you have by:

        onRequestClose={() => setIsModalOpen(false)}
        <p>id is {data[pattern].id}</p>
        <img src={data[pattern].img} alt={data[pattern].img} width="100" />

You can find working prototype at this sandbox.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.