skip to Main Content

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

  • on first click is checks correctly, shows the div, and it autofocuses
  • if i click outside the pane (anywhere), it unchecks and hides de pane well
  • the problem is that i cant hide the pane by clicking on the checkbox itself (it flashes unchecked & checked again instantly)

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)

  • The handleCheckboxStateChange function is fired only ONCE when I click the checkbox to uncheck it

2

Answers


  1. Chosen as BEST ANSWER

    As stated by @Anandhu, the problem was that when clicking in the checkbox it fired both events, selectorPane.onBlur() & checkbox.onChange(), which causes a double state change, so it flickered and remain the same.

    The optimal solution for me was checking if the new focused element is the checkbox by using the relatedTarget prop of the FocusEvent object, and skipping the state change from the onBlur() when that was the case.

    For that:

    • added a reference to checkbox element
    • on the handleSelectorPaneBlur func, skipped execution if e.relatedTarget == checkboxRef.current

    The code with this solution:

    import { useEffect, useRef, useState } from "react"
    
    import "./Selector.css"
    
    export default function Selector() {
      const selectorPaneRef = useRef<HTMLDivElement | null>(null);
      const checkboxRef = useRef<HTMLInputElement | null>(null);
     
      const [ selectorPaneVisible, setSelectorPaneVisible ] = useState(false);
    
      const handleCheckboxStateChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const checkbox = e.target as HTMLInputElement;
        setSelectorPaneVisible(checkbox.checked);
      }
    
      const handleSelectorPaneBlur = (e: React.FocusEvent<HTMLDivElement>) => {
        //let checkbox handle the state change when it is the new focused element
        if (e.relatedTarget == checkboxRef.current) {
          return;
        }
         
        setSelectorPaneVisible(false);
      }
     
      //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}
            ref={checkboxRef}
          />
          <div
            className={`selector-pane ${selectorPaneVisible ? "visible" : ""}`}
            onBlur={handleSelectorPaneBlur}
            tabIndex={-1}
            ref={selectorPaneRef}
          >
            content content content content
          </div>
        </div>
      )
    }
    

    Css didn't change:

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

    Thanks to @Anandhu for the response & @Drew Reese for edition. 😉


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search