React useClickInside Hook

ReactReactBeginner
Practice Now

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

Introduction

In this lab, we will learn how to create a custom React hook called useClickInside. This hook will handle the event of clicking inside a wrapped component and trigger a callback function. We will use useEffect() and useRef() hooks to append and clean up the click event. By the end of this lab, you will have a better understanding of how to create custom hooks and handle events in React.


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-38372{{"`React useClickInside Hook`"}} react/event_handling -.-> lab-38372{{"`React useClickInside Hook`"}} react/hooks -.-> lab-38372{{"`React useClickInside Hook`"}} react/css_in_react -.-> lab-38372{{"`React useClickInside Hook`"}} end

React useClickInside 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.

To handle a click event inside a component, you can create a custom hook called useClickInside that takes a ref and a callback. Use the useEffect() hook to append and clean up the click event, and the useRef() hook to create a ref for your click component and pass it to the useClickInside hook. Here's the code:

const useClickInside = (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);
    };
  }, [ref, callback]);
};

You can use this hook in your component like this:

const ClickBox = ({ onClickInside }) => {
  const clickRef = React.useRef();
  useClickInside(clickRef, onClickInside);

  return (
    <div
      className="click-box"
      ref={clickRef}
      style={{
        border: "2px dashed orangered",
        height: 200,
        width: 400,
        display: "flex",
        justifyContent: "center",
        alignItems: "center"
      }}
    >
      <p>Click inside this element</p>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(
  <ClickBox onClickInside={() => alert("click inside")} />
);

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 useClickInside Hook lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like