Click outside element event using React Hooks

Kevin Felisilda
2 min readMar 31, 2019

--

Have you encounter a feature that let’s you open a menu and auto-close it when you click outside that element? It’s possible in a lot of ways usually with a dedicated button to close or a backdrop which is similar to what Bootstrap uses.

Luckily, after React hooks were introduced, there’s a simple way to implement same behavior and not tied it into every component.

I run my Node.js applications on DigitalOcean droplets. If you want to give it a try with a $100 credit, simply follow this link:

The concept is to use a function that will accept element reference and a callback. This way we can separate the behavior and the component, this will also make behavior reusable and easy to maintain.

useRef

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component. https://reactjs.org/docs/hooks-reference.html#useref

We can assign the reference to any react component/element and use that to tell the hook what element you are referring to. It will then check if the click event is outside that element and trigger the callback. Pretty simple!

We can now import our custom hook file and use it just like a regular react hook.

Demo

I created a sample file you can play around with.

Further Reading

React Hooks reference: https://reactjs.org/docs/hooks-reference.html

You can check this different implementation which uses component based instead https://medium.freecodecamp.org/how-to-detect-an-outside-click-with-react-and-hooks-25dbaa30abcd.

--

--

Kevin Felisilda

I’m a Software Engineer. I like to innovate and explore new things. I love listening to music hits, joining tech talks and flying a drone.