React useClickOutside Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StylingGroup(["`Styling`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StylingGroup -.-> react/css_in_react("`CSS in React`") subgraph Lab Skills react/jsx -.-> lab-38373{{"`React useClickOutside Hook`"}} react/event_handling -.-> lab-38373{{"`React useClickOutside Hook`"}} react/hooks -.-> lab-38373{{"`React useClickOutside Hook`"}} react/css_in_react -.-> lab-38373{{"`React useClickOutside Hook`"}} end

React useClickOutside Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.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 onClickOutside={() => 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.

Other React Tutorials you may like