Sometimes, we want to fix input losing focus when rerendering with React.
In this article, we’ll look at how to fix input losing focus when rerendering with React.
How to fix input losing focus when rerendering with React?
To fix input losing focus when rerendering with React, we should define child components outside the parent component.
For instance, we write
const Child = () => <p>Child!</p>;
const Parent = () => <Child />;
to define the Child
component outside the Parent
.
And then we render the Child
component in the Parent
.
This way, when Parent
re-renders, Child
only re-renders if the props or state of it changes.
Conclusion
To fix input losing focus when rerendering with React, we should define child components outside the parent component.