Detect click outside a react component using React Hooks
Many more developers are facing difficulties to detect the click event outside of the element in ReactJS therefore we’ll show you how to detect click outside a react component using React Hooks.
Why do we need it?
In the real project, we might need to handle an event when we click outside of a react component. Based on the outside event we can show or hide the element or manage some other components.
Detect click outside a react component
Use the following code to detect outside click events.
function useVisible(initialIsVisible) {
const [isVisible, setIsVisible] = useState(initialIsVisible);
const ref = useRef(null);
const handleClickOutside = (event) => {
if (ref.current && !ref.current.contains(event.target)) {
setIsVisible(false);
}
};
useEffect(() => {
document.addEventListener('click', handleClickOutside, true);
return () => {
document.removeEventListener('click', handleClickOutside, true);
};
}, []);
return { ref, isVisible, setIsVisible };
}
In the above code, we have added the event listener of the click event and remove it on component unmount.
Also we are handling the initial state of the component for visibility and reference of the component to detect outside click.
At last we are returning the reference, visibility state and method to change the visibility state and those attributes are useful to detect outside click.
Example
Let’s take a previous example, where we have implemented color picker in react. Now we will show a color picker on click of the input field and hide it when we detect a click outside a color picker.
First, we have to create a custom hooks to detect click event. Use the below code to create a custom hooks.
useVisible.js
import { useState, useRef, useEffect } from "react";
function useVisible(initialIsVisible) {
const [isVisible, setIsVisible] = useState(initialIsVisible);
const ref = useRef(null);
const handleClickOutside = (event) => {
if (ref.current && !ref.current.contains(event.target)) {
setIsVisible(false);
}
};
useEffect(() => {
document.addEventListener('click', handleClickOutside, true);
return () => {
document.removeEventListener('click', handleClickOutside, true);
};
}, []);
return { ref, isVisible, setIsVisible };
}
export default useVisible;
Use the above hooks in the `App.js` file to manage show/hide color picker on click.
App.js
import React, { useState } from 'react';
import { SketchPicker } from 'react-color';
import useVisible from './useVisible';
function App() {
const [colorHexCode, setColorHexCode] = useState('#000000');
const { ref, isVisible, setIsVisible } = useVisible(false);
return (
<div class="App">
<h3>React color picker - <a href="https://www.cluemediator.com">Clue Mediator</a></h3>
<div>
<b>Selected Hex Color: </b>
<span class="color-box" style={{ background: colorhexcode }}></span>
{colorHexCode}
</div>
<br>
<input type="text" readonly value={colorHexCode} onclick="{e" ==""> setIsVisible(!isVisible)} />
{isVisible && <div style={{ position: 'absolute' }} ref={ref}>
<sketchpicker color={colorHexCode} onchange="{e" ==""> setColorHexCode(e.hex)} />
</sketchpicker></div>}
</div>
);
}
export default App;
We are also showing the selected color in box along with the color code for live view.
Output
Run the project and check out the output in browser.
Output - Detect click outside a react component using React Hooks - Clue Mediator
That’s it for today.
Thank you for reading. Happy Coding..!!