I have a react app where on mobile the user can click an icon to see a search input bar. The focus should go to the input element and show the keyboard if on mobile. The problem is the cursor doesn't move to the input element and the keyboard doesn't display on iPhone. Does anyone know of a fix for this?
In parent component:
const [focusSearchInput, setFocusSearchInput] = useState(false);
useEffect(() => {
if (isMobile) {
setFocusSearchInput(true);
}
}, [isMobile]);
child component:
const inputRef = useRef();
useEffect(() => {
focusSearchInput ? inputRef?.current?.focus() : inputRef?.current?.blur();
}, [focusSearchInput]);
return (
<input ref={inputRef} />
)
CodePudding user response:
@Undo's answer was right. Once I moved the focus to the actual onClick event it worked.
CodePudding user response:
Browsers are usually restrictive of automatically performing actions for the user such as copying or entering full screen. Focus the input inside the actual onClick event instead of doing it inside a useEffect.