0

I need to create Select components based on a list of selects that i have, for example:

List -> item1, item2

The component :

<Select 
  value={this.state."NAME OF THE ITEM ON THE LIST"}
  onChange={this.handleChange}
 <MenuItem value={X} key={X} > Something </MenuItem> (the MenuItem part is working)
</Select>

Since the select component needs a value and i need that value to be a state, so when it gets clicked it will call the method handleChange and will update the state like this:

handleChange = (event) => {
    this.setState({
        "THE NAME OF THE ITEM ": event.target.value(this comes from the MenuItem)
    });
};

How can i create the state dynamically so if i have a list with X itens it will create X selects and X states to be updated?

2 Answers 2

1

You can use an array property in your state to manage these items

state = {
    items: []
}

Then, when you are dynamically adding a select, you have to add a new value in this array

addItem = () => {
    this.setState({
        items: [
            ...this.state.items, // previous items
            { value: ""} // plus the new one
        ]
    });
};

And finally, when you render a Select

<Select
  value={this.state.items[index].value
  onChange={event => {
    this.setState({ // map over the array to modify the matching item
      items: this.state.items.map(
        (item, idx) =>
          idx === index ? {...item, value: event.target.value} : item
      )
    });
  }}>
Sign up to request clarification or add additional context in comments.

4 Comments

in this part : value={this.state.items[index].value}
Can u make a working example so i can compare with what i did?
Nevermind, just figure it out, but your answer give me the right path to follow, thanks
@LucioZenir What is [index]?
0

hopefully below snippet will help you,

{this.props.data.map((e, keyIndex) => {
    return (<MenuItem key={keyIndex} value={e.warehouseId}>{e.name}</MenuItem>);
 })
}

Comments

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.