React.js - Both modals close when one was supposed close and the other one open

Viewed 29

So I am trying to close one modal and open the other one, but both keep closing for no reason and I have no idea what I'm doing wrong

My Code

const Modal = ({ closeModal }) => {
  const [ openModal2, setOpenModal2 ] = useState(false)

  const closeModalFunction = () => {
    closeModal(false)
  }

  const openModal2Function = () => {
      closeModalFunction()
      setOpenModal2(true)
    }
  }

  return (
    <div className='modal'>
        <div className='modal-overlay' onClick={closeModalFunction}></div>
            <div className='open-modal-2'>
                <button className='open-modal-2-button' onClick={openModal2Function}>Continue</button>
            </div>
        </div>

        {openModal2 && <Modal2
            closeModal2={setOpenModal2}
        />}
    </div>
  )
}
1 Answers

Yes it is because your Modal2 is in your Modal1 component so when you close your Modal1, you close your Modal2 functionality as well. You can do this this way

    const Parent = () => {
    const [state, setState] = useState({
        showModal1: false,
        showModal2: false
    })
    const onCloseModal1 = () => {
        setState(prev => ({...prev, showModal1: false, showModal2: true}))
    }
    const onCloseModal2 = () => {
        setState(prev => ({...prev, showModal2: false}))
    }
    return <>
    {state.showModal1 && <Modal1 onCloseModal1={onCloseModal1} />}
    {state.showModal2 && <Modal2 onCloseModal2={onCloseModal2}/>}
    </>
}
Related