Tjm92
Tjm92

Reputation: 317

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!

Upvotes: 0

Views: 178

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371233

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

Upvotes: 1

Related Questions