1

I have a list of inputs that are generated based on the number of items in an array:

const itemInputs = items.map(
  item => <Input key={item} value={itemInput} onChange={event => this.updateItem(event)} />,
);

Here is what my updateItem function looks like:

  updateItem(event) {
    this.setState({
      itemInput: event.target.value,
    });
  }

So if there are two items in my array, then two input fields will be generated, like so: enter image description here

But when I enter a value for the first input field, that same value appears in the second input field, like so:

enter image description here

How can I prevent this from happening? I want each input field to retain its own value.

2 Answers 2

3

Here is one way to do that

const items = ['firstName', 'lastName'];

const itemInputs = items.map(
  name => <Input key={name} name={name} value={this.state[name]} onChange={event => this.updateItem(name, event)} />,
);

updateItem = (name, event) => {
  this.setState({ [name]: event.target.value });
}

Sign up to request clarification or add additional context in comments.

Comments

0

Well, I assume you are putting all the inputs in one component. And component can have only 1 state.

In other words, you are changing the value of itemInput, and it effects all inputs because ypu declared that their value would be itemInput of the same component of all.

What you can do is make a new component for input, and call it instead. That way you will have state for every single input.

Hope that helps. Good luck

1 Comment

I see. Well you are still pass those custom component the value on a single component. Which is 1 state.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.