Toggle state inside object using react hook

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!

Answer

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
}))};

Leave a Reply

Your email address will not be published. Required fields are marked *