javascripthtmlreactjsreact-ref

How can I open select box on focus?


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?


Solution

  • 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 there are some thing to be noted:

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