skip to Main Content

I want to open a select box when it gets focus. I’m using React hooks with useRef.
I found several solutions with using ref.current.click(). But it is not working as expected. Am I doing something wrong?

Here is the simplified code:

import {useRef, forwardRef} from 'react';

export default function App() {

  const ref = useRef(null);

  return (
    <div className="App">
      <input type="text" name="text" value="" onChange={(e) => console.log(e)} />
      <br />
      <br />
      <SelectBox 
        ref={ref}
      />
    </div>
  );
}

const SelectBox = forwardRef((props, ref) => {
  function onFocus() {
    if(ref.current) {
      ref.current.click();
    }
  }

  return (
    <select
      ref={ref}
      onChange={(e) => console.log(e)}
      onFocus={onFocus}
    >
      <option value="1">Test 1</option>
      <option value="2">Test 2</option>
    </select>
  )
});

Or are there other solutions to open the select box (show options) on focus?

2

Answers


  1. Behavior of opening select box is controlled by the browser. So, you are finding difficulty in opening select box using ref but you can use alternatives to achieve this functionality. Here are the codes which works for me.

            const SelectBox = forwardRef((props, ref) => {
          const [isOpen, setIsOpen] = useState(false);
    
          const handleFocus = () => {
            setIsOpen(true);
          };
    
          const handleBlur = () => {
            setIsOpen(false);
          };
    
          return (
            <select
              ref={ref}
              onChange={(e) => console.log(e)}
              onFocus={handleFocus}
              onBlur={handleBlur}
              size={isOpen ? 3 : 1} // change this as per your number of options
            >
              <option value="1">Test 1</option>
              <option value="2">Test 2</option>
              <option value="3">Test 3</option>
            </select>
          );
        });
    
    Login or Signup to reply.
  2. There is a native way to open select, and its by calling showPicker(). You can achieve it by doing something like this:

    const ref = useRef();
    
      const handleFocus = () => {
        ref.current?.showPicker();
      };
    
      return (
        <select ref={ref} onFocus={handleFocus}>
          <option>Option 1</option>
          <option>Option 2</option>
          <option>Option 3</option>
          <option>Option 4</option>
        </select>
      );
    

    However please note that showPicker() needs a transient user activation. Meaning that the user has to interact with the page or a UI element in order for this feature to work.

    MDN reference: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/showPicker

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