1

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>
1
  • please add your state and create demo if you can Commented Jan 7, 2019 at 4:27

1 Answer 1

1

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
      });
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but how can this be applied to grouped, dynamic forms?
Do you have an example?
For multiple groups : checked={this.state.optionId[option.name] === option.id} onChange(this.handleChange) I have updated the code
Had my answer helped you?

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.