I have a requirement to display an input field and focus the element on click of a button my code snippet looks like this
import { useState, useRef } from 'react';
function App() {
const inputRef = useRef(null);
const [enableSearch,setEnableSearch]=useState(false);
const handleClick= () => {
setEnableSearch(!enableSearch)
inputRef.current.focus();
}
return (
<div >
{enableSearch&&<input ref={inputRef}/>}
<button onClick={handleClick}>show input</button>
</div>
);
}
export default App;
I am not able to get the cursor focus on the input when enableSearch condition is used what is wrong in this implementation?
3
Answers
Updating state in React is asynchronous, so react will wait until all the code in the event handler has run before processing the state update. (docs)
That’s why when you’re trying to focus on the input, it will throw an error since the input doesn’t exist yet.
You could use
useEffect
to change focus when theenableSearch
value changes to trueIn your case, input field
is not rendered
because you have added conditional rendering. When you click on button , you changed value ofenableSearch
. As useState hook updater methodbehave like async
so it take may take few time and on next line you addedinputRef.current.focus()
. Again, may be your input is not rendered yet therefore it not able to fineinputRef
that is null and therefore you focus was not working.Here is updated code snippet to add focus on button click
if that’s all what you need that ref for, then you can do this:
https://reactjs.org/docs/refs-and-the-dom.html#callback-refs