I'm trying to create a dynamic form, in this form users can add as many books as they want, and each book has a name and an link.
I already have a button Add a Book and fields are added correctly in my form, but when I type in any one of these fields my input loses the focus
I'm saving books []
inside of my component state, and to update it I have an onChange={(e) => this.handleDynamicChange(e, 'fieldName', index)}
in my input.
handleDynamicChange
handleDynamicChange = (event, name, index) => {
const { value } = event.target;
let { books } = this.state;
books[index][name] = value;
this.setState({ books });
}
My input for book link (using material ui):
<TextField
id={`edit-profile-book-link-${index}`}
label='Link'
value={book.link}
onChange={(e) => this.handleDynamicChange(e, 'link', index)}
/>
I guess it's because I'm updating the entire books array, so react is re-rendering all books fields, but I couldn't find a way to update only one book using setState()
, so, do you know how to handle these updates inside of a dynamic form ?
I already saw that question but didn't help: React.js - input losing focus when rerendering
I have been checking this tutorial: building a dynamic controlled form