Six Tiny But Awesome Es7 Es8 Features

Although I love ReactJS, I can say that I sometimes find that interactions that were easy during pre-reactions are annoying or at least "indirect". An example is to make sure that a given element is well targeted when a button in a different component is clicked; in the old days, it was three lines of code, but with React it can be more.

Let's take a look at some strategies to focus on the elements with ReactJS.


The autofocus attribute is met in ReactJS but only when the element is re-rendered with React:

autofocus is easy to use but only works when is initially rendered; since React intelligently only renders the elements that have changed, the autofocus attribute is not reliable in any case.

componentDidUpdate with ref

Since we can not rely solely on the autofocus attribute, we can use componentDidUpdate to complete the objective:

Class Expressions Extend Component {

_INPUT 😕 HTMLInputElement;

// ….

componentDidUpdate (prevProps, prevState) {
this._input.focus ();

render () {
come back (

(this._input = c)}


componentDidUpdate fires after the component is updated, so any changes to the parent component would trigger this method and your would receive focus. In my case, I usually switch a className on the parent element to signal that the element is active and so the componentDidUpdate will fire.

My perspective of inter-widget interaction was formed by the days of the Dojo dijit UI framework. usually had a reference to each child widget; with ReactJS, the practice avoids (I hope) the refs and uses the state, which is logical but there is always this piece of me that aspires to a simple reference, that is why the second strategy makes sense to me.

Load More Related Articles
Load More By Amit Ghosh
Load More In Javascript

Leave a Reply

Your email address will not be published. Required fields are marked *