reactjscheckboxfocusonblur

Checkbox cannot change state when updated from onBlur event


I have a component (selector) which contains a checkbox and another div (selectorPane).

The checkbox state controls the selectorPane visibility (by assigning/not-assigning the 'visible' css class).

This works fine, the problem comes when i try to make selectorPane invisible (set checkbox.checked = false) on selectorPane.onBlur() event... in other words, close selectorPane when clicking outside.

This is the working code (without the 'click outside to close' functionality).

import { useEffect, useRef, useState } from "react"

import "./Selector.css"

export default function Selector() {
  //reference selector-pane for programatic focus
  const selectorPaneRef = useRef<HTMLDivElement | null>(null);

  const [ selectorPaneVisible, setSelectorPaneVisible ] = useState(false);

  const handleCheckboxStateChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const checkbox = e.target as HTMLInputElement;
    setSelectorPaneVisible(checkbox.checked);
  }

  //autofocus selector-pane when rendering with selectorPaneVisible = true
  useEffect(() => {
    if (selectorPaneVisible && !!selectorPaneRef.current) {
      selectorPaneRef.current.focus();
    }
  }, [selectorPaneVisible])

  return (
    <div className="selector">
      <input
        type="checkbox"
        checked={selectorPaneVisible}
        onChange={handleCheckboxStateChange}
      />
      <div
        className={`selector-pane ${selectorPaneVisible ? "visible" : ""}`}
        tabIndex={-1}
      >
        content content content content
      </div>
    </div>
  )
}

note: autofocus functionality is not used here, but is kept to demonstrate it doesn't add a bug

Here is the NOT-WORKING example:

It has added the onBlur (function: handleSelectorPaneBlur) event for the selectorPane div which performs a setSelectorPaneVisible(false)

import { useEffect, useRef, useState } from "react";

import "./Selector.css";

export default function Selector() {
  //reference selector-pane for programatic focus
  const selectorPaneRef = useRef<HTMLDivElement | null>(null);

  const [selectorPaneVisible, setSelectorPaneVisible] = useState(false);

  const handleCheckboxStateChange = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    const checkbox = e.target as HTMLInputElement;
    setSelectorPaneVisible(checkbox.checked);
  };

  const handleSelectorPaneBlur = () => {
    setSelectorPaneVisible(false);
  };

  //autofocus selector-pane when render with selectorPaneVisible = true
  useEffect(() => {
    if (selectorPaneVisible && !!selectorPaneRef.current) {
      selectorPaneRef.current.focus();
    }
  }, [selectorPaneVisible]);

  return (
    <div className="selector">
      <input
        type="checkbox"
        checked={selectorPaneVisible}
        onChange={handleCheckboxStateChange}
      />
      <div
        className={`selector-pane ${selectorPaneVisible ? "visible" : ""}`}
        tabIndex={-1}
        ref={selectorPaneRef}
        onBlur={handleSelectorPaneBlur}
      >
        content content content content
      </div>
    </div>
  );
}

By default the checkbox is unchecked, so the selectorPane is invisible

This is the CSS:

.selector > div {
  background-color: green;
}
.selector > div:focus {
  background-color: red;
}

.selector > div {
  visibility: hidden;
}
.selector > div.visible {
  visibility: visible;
}

I tested creating a ref to the checkbox element to uncheck it by firing a programatic click event

const checkboxRef = useRef<HTMLInputElement | null>(null)

<input 
  type="checkbox" 
  checked={selectorPaneVisible} 
  onChange={handleCheckboxStateChange} 
  ref={checkboxRef} 
/>
const handleSelectorPaneBlur = () => {
  if (checkboxRef.current) {
    checkboxRef.current.click();
  }
}

but the result is the same (unchecks & checks again in a flash)


Solution

  • The issue is with the onBlur callback (actually that's how it's supposed to work).

    When the checkbox is checked, it sets the focus to the selectorPane. If you click the checkbox again to toggle visibility, the focus shifts from the selectorPane to the checkbox, causing the onBlur event of the selectorPane to fire prematurely.

    This hides the selectorPane before the checkbox click event can complete, leading to flickering as the state is reset.

    To verify this issue, you can add a delay to the state update inside the onBlur callback. For example:

    const handleSelectorPaneBlur = e => {
      setTimeout(() => {
        setSelectorPaneVisible(false);
      }, 500);
    };
    

    Adding a timeout to the state update in the onBlur callback delays hiding the selectorPane, allowing the checkbox click event to complete properly.