Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React on Blur not being called

Tags:

reactjs

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?

like image 862
iRohitBhatia Avatar asked Dec 10 '25 07:12

iRohitBhatia


2 Answers

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.

like image 163
Job Ouddeken Avatar answered Dec 12 '25 23:12

Job Ouddeken


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

like image 43
soujvnunes Avatar answered Dec 12 '25 23:12

soujvnunes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!