0

I am working on displaying an overlay when a user clicks on an image. Similarly, if the overlay is already visible then I would like to close it. Below is the initial state:

const [showOverlay, setShowOverlay] = useState({
   visible: false,
   xPosition: null,
   yPosition: null
});

Here is the click event on the image element. This example works for displaying the image, but obviously it does not toggle it on/off.

onClick={(e) => setShowOverlay({
   visible: true,
   xPosition: e.pageX,
   yPosition: e.pageY
})};

I've been attempting to use "prevState" to toggle this particular property, but I haven't had any luck.

onClick={(e,prevState) => setShowOverlay({
   visible: !prevState.visible,
   xPosition: e.pageX,
   yPosition: e.pageY
})};

Any advice would be highly appreciated - thank you!

1 Answer 1

1

The second parameter to a click handler function is not the previous state of a random state value in a functional component. To get the previous state, either reference the standalone stateful variable declared up above in the component:

onClick={(e) => setShowOverlay({
   visible: !showOverlay.visible,
   xPosition: e.pageX,
   yPosition: e.pageY
})};

Or use the callback form of the state setter:

onClick={(e) => setShowOverlay(showOverlay => ({
   visible: !showOverlay.visible,
   xPosition: e.pageX,
   yPosition: e.pageY
}))};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.