Home > Enterprise >  Handling state of select tag in dynamic input field react
Handling state of select tag in dynamic input field react

Time:09-27

I do not understand why the state is registered yet it does not have an effect to the intended value of beds. Here is the main component

const options = ["1", "2", "3"];
class Apps extends React.Component {  
  constructor(props) {    
    super(props)
    this.state = { 
       formValues: [{ name: "", email : "" ,beds:[options[0]]}]
     };
    
  }  
  handleChange(i, e) {
    let formValues = this.state.formValues;
    formValues[i][e.target.name] = e.target.value;
    this.setState({ formValues });
  }
  render() {
    const {formValues} = this.state;
    return (
        <PropertyType options={options} values={formValues}  handleChange={this.handleChange.bind(this)} />
    );
  }
}

Here is the property type component. I do not understand why its not working i have tried other means if anyone is willing to take a look at the code please do so

function PropertyType({values,add,remove,options,handleChange,handleSubmit}) {

    return (
        <form  onSubmit={handleSubmit}>
          {values.map((element, index) => (
            <div className="form-inline" key={index}>
              <label>Name</label>
              <input type="text" name="name" value={element.name || ""} onChange={e => handleChange(index, e)} />
              <label>Email</label>
              <input type="text" name="email" value={element.email || ""} onChange={e => handleChange(index, e)} />
              <select 
                  value={element.beds} 
                  onChange={e => handleChange(index, e)}>
                    {options.map((value) => (
                      <option value={value} key={value}>
                        {value}
                      </option>
                    ))}
               </select>
              {
                index ? 
                  <button type="button"  className="button remove" onClick={() => remove(index)}>Remove</button> 
                : null
              }
            </div>
          ))}
          <div className="button-section">
              <button className="button add" type="button" onClick={() => add()}>Add</button>
              <button className="button submit" type="submit">Submit</button>
          </div>
      </form> );
}

enter image description here

CodePudding user response:

Your select input has no name, so when you change your select value, it updates the state reference value with "" name.

Notice the name value below:

      <select  
                  name="beds"
                  value={element.beds} 
                  onChange={e => handleChange(index, e)}>
                    {options.map((value) => (
                      <option value={value} key={value}>
                        {value}
                      </option>
                    ))}
               </select>
  • Related