React Tutorial- Detect Outside Click To Hide Dropdown Element Example

React Detect Outside Click To Hide Dropdown Element Tutorial

Friends, in this React tutorial, we will learn how to listen for clicks events that occur somewhere in our 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 a React application.

Also, this guide will be showing us the proper configuration procedure to implement on click outside element scope in React.

 

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

 

Let’s learn in detail now:

Step 1- Download React Project

Firstly, we have to download the new version of React application.

For this, we need to have the node and npm tools installed on our system.

Now, let’s start installing the React app:

npx create-react-app react-nector

Then, we move into the project’s root:

cd react-nector

 

Step 2- Design Dropdown Module

Here, we will write some custom CSS for designing our dropdown component.

We need to look for the index.css file in our app’s root after which we have to add the given 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);
}

 

Step 3- Functional Component Track Click Event

We will get to know in this step how to hide a select component’s dropdown list section when clicked outside or anywhere in the document from the functional component’s perspective.

Then, we create the components/ folder at the root of our React app. We will also create the MyDropDown.js and listen-for-outside-click.js files inside the components folder.

Next, we require to copy the given 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)
      })
    })
  }
}

In addition, we take the complete code and put it 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

 

Step 4- Invoke Dropdown Component

Afterward, we will be adding 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;

 

Step 5- Run App In Browser

Finally, we have reached the conclusion and need to test our React app.

For this purpose, we will type the command on our console’s prompt and enter to run the React server:

npm start

 

Conclusion

So, it is hoped that it’s quite clear that we have to listen to click events for handling the behavior of some UI elements.

We have learned in this tutorial how to track client events when people click outside the component or element scope.

 

Good luck!

Leave a Reply

Your email address will not be published. Required fields are marked *