Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to capture when dropdown is open on React

Is there a way to tell when the dropdown is open and also closed? onfocus and onblur doesn’t seem to be working.

<div className="select-container">
  <select>
    {options.map((option) => (
      <option value={option.value}>{option.label}</option>
     ))}
  </select>
</div

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You should use useState to keep track of the dropdown status. It would look something like this:

import "./styles.css";
import { useState } from "react";

export default function App() {

  const [isDropDownOpen, setDropDownOpen] = useState(false);

  let options = [
    {
      label: "money"
    }
  ];

  const handleSelect = () => {
    setDropDownOpen(!isDropDownOpen);
  };

  const handleBlur = () => {
    setDropDownOpen(!isDropDownOpen);
  };

  console.log(isDropDownOpen);

  return (
    <div>
      <select onBlur={handleBlur} onClick={handleSelect}>
        {options.map((option) => (
          <option value={option.value}>{option.label}</option>
        ))}
      </select>
    </div>
  );
}

I have tied it into the handleSelect function, which will probably do more than just keep track of whether or not the dropdown is open but either way, it works as a reference point for now.

EDIT: Also, in case you click outside the dropdown, I used onBlur, which is controlled by handleBlur to change the boolean value because obviously, the dropdown will close.

Check the console.log on the this code sandbox to see how it works: https://codesandbox.io/s/amazing-easley-0mf7o3?file=/src/App.js

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading