React – useRef – Open select box on focus

  Kiến thức lập trình

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?

LEAVE A COMMENT