React Hide Dropdown with Click Outside Scope Tutorial

I was recently working on a project; my task was to create every UI component from scratch. When I was working on a dropdown element, I got stuck at a stage where I had to hide the dropdown when clicking on the body.

After a lot of googling, I got a chance to know more about React useRef hook and i was amazed by the power of the useRef hook.

In this tutorial, I would like to share how I managed to track the click event outside its scope. We will learn how to work with React mutable values using the useRef useState, and useEffect hooks and understand how to capture outside click event in React Js using useRef hook.

The useRef is a React hook specially designed for React functional components. The useRef hook is used as a box for holding mutable values in a .current property with the primary purpose of enhancing the performance of the component.

The useRef directly constitutes a reference to the DOM element in the functional component. As a result, it enhances the performance of the component updates variables without causing the re-render.

The pattern of this hook makes it works smoothly with the mutable values.

How to Use React useRef Hook to Hide Dropdown Outside Click in React Js

  • Step 1: Install React App
  • Step 2: Create Component
  • Step 3: Track Click Outside Scope
  • Step 4: Register Component in App Js
  • Step 5: Run Application

Install React App

We will start installing a new react app; you may run the provided command to begin the app installing process.

npx create-react-app reactor

Head over to app folder.

cd reactor

Create Component

Components are the best way to manage the code and react’s mechanism is such where you have to create the component file to create any feature.

Hence, create the Dropdown.js, add the following code into the file and form the functional component.

import React from "react";

export default function Dropdown() {
    return (
      <> </>
    );
}

Track Click Outside Scope

Let us find out how to combine all the hooks to track the click event outside its scope.

Create the components/Dropdown.js folder and file, paste the following code into the file.

import React, { useState, useRef, useEffect } from 'react'


export default function Dropdown() {

  // define mutable val in .current object
  const node = useRef();

  // set initial state
  const [user, showText] = useState(false);
  
  // update state on button click
  const setText = (user) => {
       return showText(!user)
  }

  // Track events outside scope
  const clickOutside = (e) => {
    if(node.current.contains(e.target)) {
      // inside click
      console.log('clicked inside')
      return;
    } 
    // outside click
      console.log('clicked outside scope')
      showText(false)
  }

  // Do something after component renders
  useEffect(() => {
    document.addEventListener('mousedown', clickOutside);

    // clean up function before running new effect
    return () => {
        document.removeEventListener('mousedown', clickOutside);
    }
  }, [user])
 
  return (
    <>
       <h2>React Dropdown Show Hide Outside Click Scope Example</h2>
       
       <div className="block-one">
          <div className="block-two">
            <button ref={node} onClick={() => setText(user)}>Show Dropdown</button>
            
            <div className={user ? "show dropdown" : "hide dropdown"}>
              <a href="#">Nav</a>
              <a href="#">Nav</a>
              <a href="#">Nav</a>
              <a href="#">Nav</a>
              <a href="#">Nav</a>
              <a href="#">Nav</a>
            </div>
          </div>
       </div>
    </>
  )
}

Register Component in App Js

Next, import the Dropdown component in the App.js file and call the component in the primary app function.

import React from "react";
import './App.css';
import Home from "./components/Dropdown";


export default function App() {
  return (
    <Dropdown />
  );
}

Run Application

Here is the command that will allow you to run the react application.

npm start

Paste the given url on the browser and hit enter to view the dropdown in action.

http://localhost:3000

React Hide Dropdown with Click Outside Scope Tutorial

Summary

In this tutorial, we have found out how to use the useRef hook in React app. How to keep track of variables or mutable values without re-rendering the component. Also, we have seen the example where we updated the value by clicking outside its scope.

Ideally, we may use the useRef to manage focus, text selection, trigger imperative animations, show hide dropdown, or integrate third-party libraries.

Although, useState and useEffect cause so much re-rendering, it will be a good practice to use with the utmost discretion.