Categories
JavaScript Answers

How to fix input losing focus when rerendering with React?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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