Viper
Viper

Reputation: 1397

React Form Dynamic Input Fields

I'm trying to create a react form with multiple (dynamic) input fields. Inputs are grouped together as seen in the picture below.

enter image description here

When a user submits the form, I need to get the values selected from each group. The groups are dynamically generated using the map function. I haven't found much on this topic.

My existing code:

<form onSubmit={this.handleSubmit.bind(this)}>
  <div className="container">
    {this.state.food.options.map((food, i) =>
      <div key={i}>
        <h5 style={{marginBottom: 2}}><b>{food.name}</b></h5><br />
          <div>
            {food.options.map((option, k) =>
              <div className="row" key={k}>
                <div className="col-3" style={{flex: '0 0 10%'}}>
                  <input type="radio" name={option.name} value={option.id} style={{height: 20}} />
                </div>
                <div className="col-3">
                  <span style={{paddingTop: 10, fontSize: 12}}>{option.name}</span>
                </div>
              </div>
              )}
            </div>
            <hr />
          </div>
          )}
      </div>
    </form>

Upvotes: 1

Views: 224

Answers (1)

31113
31113

Reputation: 409

You have to use checked attribute instead

And use onChange event for select optionID

<input 
type="radio" 
name={option.name} 
value={option.id} 
style={{height: 20}}  
checked={this.state.optionId[option.name] === option.id}
onChange(this.handleChange)
/>


handleChange = e => {
    this.setState({
      optionId: e.target.value
      });
}

Upvotes: 1

Related Questions