简体   繁体   中英

Multiple Modals with React Hooks

I´m building some modals for fun but I can´t make it work for multiple modals.

useModal hook

import { useState } from 'react';

const useModal = () => {

    const [isShowing, setIsShowing] = useState(false);

    const toggle = () => {
        setIsShowing(!isShowing);
    }

    return {
        isShowing,
        toggle,
    }
};

export default useModal;

Modal component

import React, { useEffect } from 'react';

const Modal = (props) => {

    const { toggle, isShowing, children } = props;

    useEffect(() => {

        const handleEsc = (event) => {
            if (event.key === 'Escape') {
                toggle()
            }
        };

        if (isShowing) {    
            window.addEventListener('keydown', handleEsc);
        }

        return () => window.removeEventListener('keydown', handleEsc);

    }, [isShowing, toggle]);

    if (!isShowing) {
        return null;
    }

    return (
        <div className="modal">
            <button onClick={ toggle } >close</button>
            { children }
        </div>
    )
}

export default Modal

in my Main component

If I do this the only modal in the page works fine

const { isShowing, toggle } = useModal();
...
<Modal isShowing={ isShowing } toggle={ toggle }>first modal</Modal>

but when I try to add another one it doesn´t work. it doesn´t open any modal

const { isShowingModal1, toggleModal1 } = useModal();
const { isShowingModal2, toggleModal2 } = useModal();
...
<Modal isShowing={ isShowingModal1 } toggle={ toggleModal1 }>first modal</Modal>
<Modal isShowing={ isShowingModal2 } toggle={ toggleModal2 }>second modal</Modal>

what I´m doing wrong? thank you

if you want to check it out please go to https://codesandbox.io/s/hopeful-cannon-guptw?fontsize=14&hidenavigation=1&theme=dark

Try that:

const useModal = () => {
  const [isShowing, setIsShowing] = useState(false);

  const toggle = () => {
    setIsShowing(!isShowing);
  };

  return [isShowing, toggle];
};

then:

export default function App() {
  const [isShowing, toggle] = useModal();
  const [isShowingModal1, toggleModal1] = useModal();
  const [isShowingModal2, toggleModal2] = useModal();

if you have multiple modal then dynamically inject <div> inside the page body and map modal to it. to create div use,

    var divTag = document.createElement("div");
    divTag.setAttribute('id', 'modal');
    document.getElementsByTagName('body')[0].appendChild(divTag);
    document.getElementById('modal').innerHTML = modalHtML;

This should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM