1

I am not sure but onblur doesn't seem to be working for me.

So this the component I have

export default function Dropdown({
  onChange,
  value,
  placeholder,
  options,
  error,
}) {
  const [showOptions, setShowOptions] = useState(false);

  const hideDropdown = () => {
    console.log("Hello");
    if (showOptions) {
      setShowOptions(false);
    }
  };
  useEffect(() => {
    if (showOptions) {
      hideDropdown();
    }
  }, [value]);
  return (
    <DropdownMain>
      <div onClick={() => setShowOptions(!showOptions)} onBlur={hideDropdown}>
        <Select>
          {value !== null ? _.find(options, { value }).label : placeholder}
        </Select>
      </div>
      <SelectIndicator></SelectIndicator>
      {showOptions &&
        (options || []).map((option, indez) => (
          <Option
            onClick={() => onChange(option.value)}
            key={`dropdownOption${indez}`}
          >
            {option.label}
          </Option>
        ))}
    </DropdownMain>
  );
}

I expect it to lose focuse when user clicks somewhere else and dropdown should close and for that I was using onBlure but that doesn't seem to be working. Any Idea on how I can fix it?

Alwaysblue
  • 9,948
  • 38
  • 121
  • 210

3 Answers3

6

The problem here is that the div you added the onBlur on never receives focus. This results in the onBlur not being fired at all, since onBlur is only fired when an element loses focus. Try adding the onBlur on the actual component that receives the focus.

Job Ouddeken
  • 183
  • 1
  • 8
  • That div does not receive focus. Adding an onClick does not add focus to that element as long as that element does not have tabindex="0". Take a look at this answer about focus on elements: https://stackoverflow.com/questions/1599660/which-html-elements-can-receive-focus – Job Ouddeken Jul 29 '20 at 21:29
0

Add tabindex={0}, so the element div can be focusable.

soujvnunes
  • 73
  • 1
  • 7
0

Place a tabIndex to make it focusable, and its important that this property is before your event caller, otherwise it won't work

// ...
<div tabIndex={0} onClick={() => setShowOptions(!showOptions)} onBlur={hideDropdown}>
  <Select>
    {value !== null ? _.find(options, { value }).label : placeholder}
  </Select>
</div>
// ...