how react programmatically focus input
The way you have used refs is not the most preferred way or else its not the best practice anymore . try some thing like this
class MyClass extends React.Component { constructor(props) { super(props); this.focus = this.focus.bind(this); } focus() { this.textInput.current.focus(); } render() { return ( <div> <input type="text" ref={(input) => { this.textInput = input; }} /> <input type="button" value="Set Focus" onClick={this.focus} /> </div> ); }}
Update
From React 16.3 upwards you can use the React.createRef()
API
class MyClass extends React.Component { constructor(props) { super(props); // create a ref to store the textInput DOM element this.textInput = React.createRef(); this.focus = this.focus.bind(this); } focus() { // Explicitly focus the text input using the raw DOM API // Note: we're accessing "current" to get the DOM node this.textInput.current.focus(); } render() { // tell React that we want to associate the <input> ref // with the `textInput` that we created in the constructor return ( <div> <input type="text" ref={this.textInput} /> <input type="button" value="Set Focus" onClick={this.focus} /> </div> ); }}
useFocus hook
// General Focus Hookconst useFocus = (initialFocus = false, id = "") => { const [focus, setFocus] = useState(initialFocus) const setFocusWithTrueDefault = (param) => setFocus(isBoolean(param)? param : true) return ([ setFocusWithTrueDefault, { autoFocus: focus, key: `${id}${focus}`, onFocus: () => setFocus(true), onBlur: () => setFocus(false), }, ])}const FocusDemo = () => { const [labelStr, setLabelStr] = useState("Your initial Value") const [setFocus, focusProps] = useFocus(true) return ( <> {/* React.Fragment */} <input onChange={(e)=> setLabelStr(e.target.value)} value={labelStr} {...focusProps} /> <h3 onClick={setFocus}>{labelStr}</h3> </> ) }
For a more complete demo click here.