Focus scroll on React element after render
Hello everybody,
You made need to put the browser’s focus on a scrollable element, just after rendering.
Using the element.focus()
is the good way to go but there a couple of tricks you should be aware of.
- The element should have a
tabindex
attribute. Setting it to “-1” will do the job. In JSX you can define it as follows:render() { return ( <div tabIndex="-1" > Lorem ipsum sic amet... </div> ); }
Once the
tabindex
attribute is set. You can call thefocus
function on it. - You can use React “ref” instead of querying the dom.
render() { return ( <div tabIndex="-1" ref={(element) => { this.ele = element; }} > Lorem ipsum sic amet... </div> ); }
- Call the focus on the
componentDidMount
lifecycle function.componentDidMount() { this.ele.focus(); }
There you have a clean focus call based on React lifecycle.
WARNING: Checking that <code>this.ele</code> exists before running the focus or running it in the <code>componentDidUpdate</code> function may be more appropriate for certain applications. Please be aware of your dom manipulations.
No comments yet.