Home > Back-end >  Reusable Modal in React
Reusable Modal in React

Time:11-19

I have data

const data  = [
      {
         id: "React",
        img: "https://cdn.worldvectorlogo.com/logos/react-2.svg",
       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 
       class."},
      }, 
      {"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.

Questions:

  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}>
      React
      <Modal open={isOpen}/>
    </button>

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

Modal Component

Import data from './data.js'

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

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

CodePudding user response:

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";
Modal.setAppElement("#root");

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

{data.map((item, index) => (
        <div>
          <button
            onClick={() => {
              setIsModalOpen(true);
              setPattern(index);
            }}
          >
            {item.id}
          </button>
        </div>
      ))}

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:

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

You can find working prototype at this sandbox.

  • Related