Introduction
In this lab, we will be learning how to use the useClickOutside hook in React to handle click events that occur outside of a specific component. This custom hook allows us to easily detect when a user clicks outside of a specific component and perform an action based on that event. By the end of the lab, you will have a better understanding of how to use this hook to create more interactive and user-friendly components in your React applications.
React useClickOutside Hook
index.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.css.
This code handles the event of clicking outside of a wrapped component. It works by creating a custom hook that takes a ref and a callback to handle the click event. The useEffect() hook is used to append and clean up the click event, while the useRef() hook is used to create a ref for the click component and pass it to the useClickOutside hook.
const useClickOutside = (ref, callback) => {
const handleClick = (e) => {
if (ref.current && !ref.current.contains(e.target)) {
callback();
}
};
React.useEffect(() => {
document.addEventListener("click", handleClick);
return () => {
document.removeEventListener("click", handleClick);
};
});
};
const ClickBox = ({ onClickOutside }) => {
const clickRef = React.useRef();
useClickOutside(clickRef, onClickOutside);
return (
<div
className="click-box"
ref={clickRef}
style={{
border: "2px dashed orangered",
height: 200,
width: 400,
display: "flex",
justifyContent: "center",
alignItems: "center"
}}
>
<p>Click out of this element</p>
</div>
);
};
ReactDOM.createRoot(document.getElementById("root")).render(
<ClickBox => alert("click outside")} />
);
Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.
Summary
Congratulations! You have completed the React useClickOutside Hook lab. You can practice more labs in LabEx to improve your skills.