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?
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:
showPicker()
needs a transient user activation. This means that the user has to interact with the page or a UI element in order for this feature to work.showPicker()
on a component inside cross-origin frame since they would cause SecurityError
as stated in the docs. This means that using CodePen or CodeSandbox to try this might not resulting the expected outcome.MDN reference: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/showPicker