React open/close modal component onClick

I currenly have a DashboardTableSection component which has a datatable in it. Inside the table there is a button, and if I click on the button a modal should open. The modal is based in its own DashboardModalSection component. Currently I have:

const DashboardTableSection = () => {
  const [showModal, setShowModal] = useState(false);

  function addItem() {
    setShowModal(true);
  }
return (
    <div>
      <MDBDataTable
        data={data}
        striped
        bordered
        small
        info={false}
        searching={false}
        proSelect
      ></MDBDataTable>
      {showModal && <DashboardModalSection title="Create Group" toggle={showModal} />}
    </div>
  );
}

Once addItem() gets called the state of showModal gets changed to true, and the modal should be shown. I pas a “toggle” prop into the DashboardModalSection component to control the state of the component. Inside DashboardModalSection the prop is passed into the “isOpen” propertly of the modal, like this:

const DashboardModalSection = (props) => {
  const [toggle, setToggle] = useState(props.toggle);

  return (
    <MDBContainer>
      <MDBModal centered isOpen={toggle}>
        <MDBModalFooter>
          <MDBBtn onClick={() => setToggle(!toggle)} color="danger">Close</MDBBtn>
        </MDBModalFooter>
      </MDBModal>
    </MDBContainer>
  );
}

So the idea is once the toggle prop gets passed into DashboardModalSection it gets passed directly into the state, basically controlling when to show the modal and when to hide it. The problem however is that this only works once. As soon as the onClick on the close button is called the component unmounts and the state returns to false. If i call then call the addItem() method agian the state dus not update anymore thus the modal stays hidden. Anyone has an idea on how to fix this issue?

Answer

You’ve created a second source of truth for the value. It’s originally controlled by the showModal value in DashboardTableSection…but then, you capture that value in DashboardModalSection’s state and pass that copy down to the MDBBtn. All that does is confuse things and cause problems like you’re seeing.

The solution is to remove the useState in DashboardModalSection and, instead of sending showModal to DashboardModalSection, give it setShowModal and have the MDBBtn setShowModal(false) to close. Don’t worry about setting it to true in there, as that is already handled in addItem way back up in DashboardTableSection.