Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

click handler not toggling state

I’m trying to create a simple app where if you click on a button, a modal overlay appears, and if you click on the ‘x’ in the modal it disappears.
I made a component for my button, called ShowOffer, and I have an onclick on it which toggles the boolean value of modalVisible, which is a piece of state.
However, nothing happens when I click on it.
I made another button element with the same onclick, and it seems to work fine.
Here is a code sandbox

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are adding onClick on the ShowOffer component, but here you are just passing it as a prop in it.

<ShowOffer display={"block"} onClick={toggleVisibility} />

is same as

React.createElement(ShowOffer, {
  display: "block",
  onClick: toggleVisibility
});

Under the hook, you are just passing an argument to a function

You have to add onClick event on the button in ShowOffer component as:

Live Demo

Codesandbox Demo

<button
      style={{ display: `${display}` }}
      onClick={toggleVisibility}
      className="show-offer"
    >
      Show Offer
    </button>

and you have to pass the toggleVisibility callback to ShowOffer as:

<ShowOffer display={"block"} toggleVisibility={toggleVisibility} />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading