React Tutorials

React Detect Outside Click to Hide Dropdown Element Tutorial

How do you listen to click events in React functional component especially when user clicks outside the component scope or anywhere in your react document?

Recently, I was creating a custom dropdown component. I almost developed it; however, at the last moment, I got stuck.

Well, It is obvious as you move forward in your React development journey, you face peculiar new challenges.

I had to close the dropdown list section by clicking outside the dropdown scope. After doing some research, I found a profound solution to track the click event.

In this post, you will find how to listen for clicks event that occur somewhere in your React document. We will detect the click event and use it to close the dropdown ui component when the user clicks outside the element scope in React application.

To give you the clear picture, we will start with creating a basic app, creating component, design dropdown using custom CSS. Most importantly, it shows you the proper configuration procedure to implement on click outside element scope in React.

Let us checkout the most straightforward approach:

How to Listen to Click Event and Hide Dropdown When Clicked Somewhere in React

  • Step 1: Download React Project
  • Step 2: Design Dropdown Module
  • Step 3: Functional Component Track Click Event
  • Step 4: Invoke Dropdown Component
  • Step 5: Run App in Browser

Download React Project

We are about to download a new version of React application.

Ensure that you have configured the node and npm tools on your development machine.

Let’s get started app installation process using the given below command.

npx create-react-app react-nector

Next, jump into the project’s root.

cd react-nector

Design Dropdown Module

Like a potter gives amazing shape to mud, likewise CSS does the same. We are going to write some custom CSS to design our dropdown component.

Look for the index.css file in your application’s root, after that add the following code into the file.

body {
  padding: 20px;
}

h2 {
  margin-bottom: 20;
}

ul,
ol {
  list-style: none;
  margin: 0;
  padding: 0;
}

.dropdownBlock {
  width: 320px;
  margin: 40px auto;
}

.dropdownActive {
  font-size: 18px;
  cursor: pointer;
  padding: 12px 20px;
  text-align: left;
  background: rgb(255 192 213);
  width: 100%;
}

.dropdownElBlock {
  margin: 0px;
  padding: 6px;
  border: 1px solid;
}

.dropdownEle.active {
  background: #f4e8d7;
}

.dropdownEle {
  text-align: left;
  padding: 5px 15px;
  cursor: pointer;
  margin-bottom: 2px;
}
.dropdownEle:hover {
  background: rgb(232, 227, 227);
}

Functional Component Track Click Event

Here we will teach you how to hide a select component’s dropdown list section when clicked outside or anywhere in the document from functional component’s perspective.

Create the components/ folder at the root of our react app. Also, create the MyDropDown.js and listen-for-outside-clicks.js files inside the components folder.

Next, copy the following code and paste in listen-for-outside-clicks.js file.

export default function listenForOutsideClicks(
  listening,
  setListening,
  menuRef,
  setIsOpen,
) {
  return () => {
    if (listening) return
    if (!menuRef.current) return
    setListening(true)
    ;[`click`, `touchstart`].forEach((type) => {
      document.addEventListener(`click`, (evt) => {
        const cur = menuRef.current
        const node = evt.target
        if (cur.contains(node)) return
        setIsOpen(false)
      })
    })
  }
}

Also, take the entire code and put inside the MyDropDown.js file.

import React, { useEffect, useState, useRef } from 'react'
import listenForOutsideClick from './listen-for-outside-clicks'

function MyDropDown() {
  // Get selected item from dropdown
  // Set active class on list item
  const [chosenVal, initChosenVal] = useState('')
  const getSelectedEl = (val) => {
    return initChosenVal(val)
  }

  // Hide and show dropdown
  const [isOpen, setIsOpen] = useState(false)
  const toggle = (isOpen) => {
    return setIsOpen(!isOpen)
  }

  // Hide Dropdown on Outside Click
  const menuRef = useRef(null)
  const [listening, setListening] = useState(false)
  useEffect(listenForOutsideClick(listening, setListening, menuRef, setIsOpen))

  // List items
  const optList = [
    {
      id: 1,
      course: 'React',
    },
    {
      id: 2,
      course: 'Vue',
    },
    {
      id: 3,
      course: 'Ionic',
    },
    {
      id: 4,
      course: 'Laravel',
    },
    {
      id: 5,
      course: 'Python',
    },
  ]

  return (
    <div>
      <h2>React Close Dropdown On Component Outside Click Example</h2>

      <div className="dropdownBlock" ref={menuRef}>
        <button
          className="dropdownActive"
          onClick={() => {
            toggle(isOpen)
          }}
        >
          {chosenVal === '' ? 'Choose course' : `Chosen course : ${chosenVal}`}
        </button>
        {isOpen ? (
          <ul className="dropdownElBlock">
            {optList.map((item) => {
              return (
                <li
                  key={item.id}
                  onClick={() => {
                    getSelectedEl(item.course)
                  }}
                  className={
                    chosenVal === item.course
                      ? 'dropdownEle active'
                      : 'dropdownEle'
                  }
                >
                  {item.course}
                </li>
              )
            })}
          </ul>
        ) : (
          ''
        )}
      </div>
    </div>
  )
}

export default MyDropDown

Invoke Dropdown Component

We have indeed implemented the code to detect outside click of component scope.

Furthermore, we require to add the MyDropDown component in the primary src/App.js template.

import React from 'react'
import MyDropDown from './components/MyDropDown.js'

function App() {
  return (
    <div>
      <MyDropDown />
    </div>
  )
}

export default App;

Run App in Browser

Eventually we have reached to the stage where we only need to test out what we have developed so far.

On your console’s command prompt, type the following command and press enter to run the react server.

npm start

On this given below url you can view and use the dropdown component.

http://localhost:3000

Conclusion

While developing React app, you have to listen to click events for handling the behavior of some UI elements.

In this tutorial, we showed you how to track click events when people click outside the component or element scope. We have described how to do it in functional component.

We hope this comprehensive guide has helped you and given you a clear understanding of the topic.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.

Recent Posts

React Redux Handle API Calls with Thunk Middleware Tutorial

In this post, we will learn how to work with HTTP requests in the Redux…

1 day ago

Node AJAX Retrieve Records from MySQL Database Tutorial

MySQL is a relational database management system based on SQL – Structured Query Language, and…

4 days ago

React Manage REST API State Globally with Context API Tutorial

React Js Handle Rest API data globally with Context and useState hook tutorial. In this…

1 week ago

How to Delete Data from MySQL Database using Node Js

Node js delete data from MySQL database tutorial; Throughout this guide, you will ascertain how…

1 week ago

Node Import CSV File Data to MySQL Database with HTML Form

In this tutorial, you will discover how to import CSV file into MySQL database using…

2 weeks ago

How to Handle Global State in React js using Context API

React Js Global state management with createContext hook example; In this tutorial, we will help…

2 weeks ago