Search code examples
javascriptreactjsmodal-dialogreact-component

How do I open a modal/ dialog from a button from nav bar component in every page react


when I click the icon from the topnav component to open modal ,the modal does not open but "modal open" text is console logged . The Top nav component has a fixed height in the main page. I need to be able to open this modal in every page that's why I added it to Nav-bar .

Topnav component

export default function Topnav({ page }) {
  const [show, setShow] = useState(false);
  return (
    <nav className="top-nav">
        <icon className='btn' onClick={() => {setShow(!show)}}>
          <VscOrganization size={20} />
        </icon>
      <h4 className="title">{page}</h4>
      
     <Modal show={show}/>
    </nav>
  );
}

modal

function Modal({ show }) {
  const classes= useStyles();
  const [open, setOpen] = useState(show);
  const [modalStyle] = useState(getModalStyle);

  return (
    <div>
      <Modal open={open} onClose={() => setOpen(false)}>
        <div style={modalStyle} className={classes.paper + " modal"}>
          <div>
            this is the modal text
            {console.log('modal open')}
          </div>
        </div>
      </Modal>
    </div>
  );
}

Solution

  • Instead of using two states for opening and closing, you need just one in the Topnav component.

    Here is what I mean:

    Topnav component: add onClose to the modal

    export default function Topnav({ page }) {
      const [show, setShow] = useState(false);
      return (
        <nav className="top-nav">
            <icon className='btn' onClick={() => {setShow(true)}}>
              <VscOrganization size={20} />
            </icon>
          <h4 className="title">{page}</h4>
          
         <Modal show={show} onClose={() => setShow(false)}/>
        </nav>
      );
    }
    
    

    modal: remove the open state and just use the props

    function Modal({ show, onClose }) {
      const classes= useStyles();
      const [modalStyle] = useState(getModalStyle);
    
      return (
        <div>
          <Modal open={show} onClose={onClose}>
            <div style={modalStyle} className={classes.paper + " modal"}>
              <div>
                this is the modal text
                {console.log('modal open')}
              </div>
            </div>
          </Modal>
        </div>
      );
    }