Skip to content

Instantly share code, notes, and snippets.

@nirsky
Last active June 9, 2020 08:53
Show Gist options
  • Save nirsky/1eeccc4f1c2268b5c18ae01831cf233f to your computer and use it in GitHub Desktop.
Save nirsky/1eeccc4f1c2268b5c18ae01831cf233f to your computer and use it in GitHub Desktop.
//Class
class InputWithFocus extends React.Component {
constructor() {
super();
this.inputRef = null;
}
render() {
return <div>
<input ref={inputRef => { this.inputRef = inputRef }} />
<button onClick={() => this.inputRef.focus()}>
Focus the input
</button>
</div>
}
}
//Hooks
const InputWithFocus = (props) => {
const inputRef = useRef();
return <div>
<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>
Focus the input
</button>
</div>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment