Emma
Emma

Reputation: 317

onClick function only works for the first time in react?

I have two seperate components namely Header and Modal. There is a button in Navbar that has an onClick function attached to it. By clicking it the state changes and hence the state is passed to modal as props which then triggers it. The state is then set to false again. However if i click on the button again, the modal does not appear. I have tried many different thing even with useEffects but nothing worked.

Header code

const Header = () => {
const [modal, setModal] = useState(false)

return( 
<div>
{modal ? <ModalProduct showModal={true} /> : null}
<ul class="nav navbar-nav ml-auto">
         <li><Button variant="danger" style={{ marginTop: '8px' }} onClick={() => setModal(true)}>Add 
         new product</Button></li></ul>)
 </div>)

And for the Modal Component I have

export default function ModalProduct(props) {
const [show, setShow] = useState(props.showModal);

const handleClose = () =>
    setShow(false);

return (
    < div >
        <Modal show={show} onHide={handleClose}>
           ...
        </Modal>
    </div >
);

}

There is something related to do with hooks, it gets true for the first time popping the modal and then changes to false but then does not become true again.

Upvotes: 2

Views: 2281

Answers (2)

oemera
oemera

Reputation: 3443

You are using 2 states for the same thing (showing/hiding the modal). You only need one state for that. Remove the state from your ModalProduct component and just use the props from your parent component Header to handle the modal. I also refactored your code to make it more concise and readable.

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

  return( 
    <div>
      <ModalProduct showModal={modal} handleClose={()=> setShowModal(false)} />
        <ul class="nav navbar-nav ml-auto">
            <li>
              <Button variant="danger" style={{ marginTop: '8px' }} onClick={()=>setShowModal(true)}>
                  Add new product
              </Button>
            </li>
        </ul>
</div>
export default function ModalProduct(props) {
  return (
    <Modal show={props.showModal} onHide={props.handleClose}>
      ...
    </Modal>
  );
}

Upvotes: 0

Oliver Heward
Oliver Heward

Reputation: 461

Point the onClick to a function that will handle the switching of the state by if true->false and false->true.

const Header = () => {
const [modal, setModal] = useState(false)

const triggerModel = () => {
  setModal(!modal)
}

return( 
<div>
{modal ? <ModalProduct showModal={triggerModel} /> : null}
<ul class="nav navbar-nav ml-auto">
         <li><Button variant="danger" style={{ marginTop: '8px' }} onClick={() => setModal(true)}>Add 
         new product</Button></li></ul>)
 </div>)

Upvotes: 1

Related Questions