How to set focus on an input field after rendering?
@Dhiraj's answer is correct, and for convenience you can use the autoFocus prop to have an input automatically focus when mounted:
<input autoFocus name=...
Note that in jsx it's autoFocus
(capital F) unlike plain old html which is case-insensitive.
You should do it in componentDidMount
and refs callback
instead. Something like this
componentDidMount(){ this.nameInput.focus(); }
class App extends React.Component{ componentDidMount(){ this.nameInput.focus(); } render() { return( <div> <input defaultValue="Won't focus" /> <input ref={(input) => { this.nameInput = input; }} defaultValue="will focus" /> </div> ); }} ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script><div id="app"></div>
Focus on mount
If you just want to focus an element when it mounts (initially renders) a simple use of the autoFocus attribute will do.
<input type="text" autoFocus />
Dynamic focus
to control focus dynamically use a general function to hide implementation details from your components.
React 16.8 + Functional component - useFocus hook
const FocusDemo = () => { const [inputRef, setInputFocus] = useFocus() return ( <> <button onClick={setInputFocus} > Focus </button> <input ref={inputRef} /> </> ) }
const useFocus = () => { const htmlElRef = useRef(null) const setFocus = () => {htmlElRef.current && htmlElRef.current.focus()} return [ htmlElRef, setFocus ] }
React 16.3 + Class Components - utilizeFocus
class App extends Component { constructor(props){ super(props) this.inputFocus = utilizeFocus() } render(){ return ( <> <button onClick={this.inputFocus.setFocus}> Focus </button> <input ref={this.inputFocus.ref}/> </> ) } }
const utilizeFocus = () => { const ref = React.createRef() const setFocus = () => {ref.current && ref.current.focus()} return {setFocus, ref} }