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
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.
There is a native way to open select, and its by calling
showPicker()
. You can achieve it by doing something like this: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