Maria Jeysingh Anbu
Maria Jeysingh Anbu

Reputation: 3312

React | Single onchange method for multiple dynamic select box

I'm getting response from API like below json. By using that response I'm generating dynamic select.

Issue: Not able to select different value for different selectbox. I'm trying to achieve with state. How to declare state dynamically in this case.

JSON

const jsonFields = {
  fields: [
    { name: "sex", value: ["m", "f"] },
    { name: "age", value: ["10", "20"] }
  ]
};

note: I don't know json key name like sex and age. name will be dynamic

Select Change:

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

Loading fields:

loadfields = () => {
    const FieldsArray = [];
    let FieldsData = jsonFields.fields;
    FieldsData.forEach((val, index) => {
      let FieldsDatavalue = val.value;
      FieldsArray.push(
        <FormControl>
          <InputLabel htmlFor="controlled-open-select">{val.name}</InputLabel>
          <Select
            value=""
            onChange={this.handleChange}
            inputProps={{
              name: "age"
            }}
          >
            {FieldsDatavalue.map(option => (
              <MenuItem key={option} value={option}>
                {option}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
      );
    });
    return FieldsArray;
  };

Scenario : Code Sandbox

Upvotes: 5

Views: 1467

Answers (1)

Oblosys
Oblosys

Reputation: 15106

You're not storing the selected value in your state, and the name in inputProps is hard coded to 'age'. If you fix those problems, it works:

      <Select
        value={this.state[val.name] ? this.state[val.name] : ''}
        onChange={this.handleChange}
        inputProps={{name: val.name}}
      >

Here's a CodeSandbox link.

UPDATE: The undefined values cause the label to overlap with the selected value, and since you retrieve them dynamically and cannot initialize them in the state, you can use a conditional this.state[val.name] ? this.state[val.name] : '' to fix the labels. (sandbox has been updated)

Upvotes: 2

Related Questions