Skip to content
Advertisement

Closing a modal on clicking outside it with React Hooks

I’m trying to create a pop up subscription box which closes whenever one clicks on the close button or clicks anywhere outside the pop up. I’ve created a modal component and a state showModal which is used to toggle the visibility of this Modal. I have tried to add setShowModal(false) to the outer div element but that just disables the whole modal. What can be done to close the modal whenever we click outside the modal. This is how my main page looks

JavaScript

Advertisement

Answer

You can use the useOnClickOutside hook. This hook allows you to detect clicks outside of a specified element.

You have to import the followings

Create a ref that we add to the element for which we want to detect outside clicks

JavaScript

State for our modal

JavaScript

Call hook passing in the ref and a function to call on outside click

JavaScript

render here

return(…);

JavaScript

See related repl output here – https://spanishhotloaderprogram.thelovekesh.repl.co/

Advertisement