How to fix undefined state passed as props, into child component?

Viewed 31

I have a parent element which passes its state value, down as props, into its Child component. Now, whenever I try to access the the state of the parent, in the child component(using props), the props value is undefined. (props of child is undefined when I pass it into useState(), but is defined when i console.log() it)

Here's the parent code:




function Parent() {

  const [openModal, setOpenModal] = useState('close-modal')


  const revealStats = (e) => {
    e.preventDefault();
    //open modal state
    setOpenModal('open-modal')
  };

  return (
    <>
    <div className='player-wrapper' key={key} onClick={(event) => revealStats(event)}>
        <ModalClubPages openModal={openModal}/>
    </div>
    </>
  );
}

export default Parent;

Here's the childs code:

function ModalClubPages({openModal}) {
    const [modalState,setModalState] = useState(openModal)
    const closeModal = (e) =>{
        e.preventDefault();
        setModalState('close-modal')
    }

  return (
    <div id={modalState}>
        <button id="close" onClick={closeModal}> X </button>
    </div>
  )
}

export default ModalClubPages
1 Answers

When passing the state from the parent to the child via props, you don't need to set a state in the child. In addition, setting it as the initial state useState(openModal) means that changes to the prop openModal won't reflect in the child's state.

Since you want to close the modal (the child) from the modal itself, the child would need to change the state of the parent. To do this, you'll need to pass a function from the parent to the child:

const { useState } = React

function ModalClubPages({ isModalOpen, closeModal }) {
  return (
    <div style={{ display: isModalOpen ? 'block' : 'none' }}>
      <button id="close" onClick={closeModal}>Child - X </button>
    </div>
  )
}

function Parent() {
  const [isModalOpen, setIsModalOpen] = useState(false)

  const revealStats = (e) => {
    e.preventDefault()
    
    setIsModalOpen(true) //open modal state
  };
  
  const hideState = () => {
    setIsModalOpen(false) //close modal state
  }

  return (
    <div>
      <button onClick={revealStats}>Parent - Open modal</button>
      <ModalClubPages isModalOpen={isModalOpen} closeModal={hideState} />
    </div>
  );
}

const root = ReactDOM.createRoot(document.querySelector('#root'));
root.render(<Parent />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

<div id="root"></div>

Related