g5insider
g5insider

Reputation: 119

How to Handle React setState() when dealing with input fields?

I have 3 text boxes. I have 1 dropdown menu.

When the app starts/page loads, the text boxes are empty and the dropdown is populated with various products.

When I select an item from the dropdown list I load the object into the text fields for editing.

When using properties (this.props), the data loads into the text boxes correctly but I can't make edits to the text because that should be done using state instead.

But, if I use state (this.state), the component never stays in sync. If I select Item 1 from the dropdown it gets loaded into the state but does not render onto the screen until I choose another Item from the dropdown list.

So when I pick Item 2 it then loads Item 1 into the text boxes.

Quote from the React docs.

"setState() does not immediately mutate this.state but creates a pending state transition"

How the heck do you guys deal with this? I feel like I've tried it all.

Upvotes: 0

Views: 404

Answers (1)

Ville Miekk-oja
Ville Miekk-oja

Reputation: 20925

You need to keep the state in the parent component. The parent would be parent for all those text boxes and to the dropdown menu. From there, you just need to pass callback functions as props to the text boxes and to the dropdown component. In that callback function, you should give the selected dropdown menu item as parameter. And when the function is called, you need to update the content of the text boxes. I think you can do this by keeping state for the three text boxes, that what text is currently displayed. Initially their state would be undefined, so they would show empty. In the state you could track the index and the value.

After that, you need to also pass callback functions to the textboxes. Those callback functions would then track and update the content of the dropdown menu items as you edit the fields. When you edit, you will call the callback, which should update the state, and also render the dropdown menu again with the new content.

Upvotes: 1

Related Questions