React - How to get input from looped <form>?

Viewed 277

I am new on React. I have a condition which is to loop the form, please help me

Here is the code:

this.state.products.map(product => {
   <form onSubmit={this.handleSubmit}>
        <select name="size" className="form-control" style={{height: '46px;'}}>
           <option key="1" value="1">Red</option>
           <option key="2" value="2">Yellow</option>
           <option key="3" value="3">Green</option>
         </select>
        <input type="submit" value="Pick This" className="form-control" onClick={() => this.handleSubmit} />
   </form>
});

If there was 3 form, how to get the selected value from clicked submit button form? Or is there another simple way? Thank you

2 Answers

One method would be changing how your onSubmit function is handled.

So you could pass which index of products you are submitting like so

this.state.products.map((product, i) => {
   <form onSubmit={event => this.handleSubmit(event, i)}>
        <select name="size" className="form-control" style={{height: '46px;'}}>
           <option key="1" value="1">Red</option>
           <option key="2" value="2">Yellow</option>
           <option key="3" value="3">Green</option>
         </select>
        <input type="submit" value="Pick This" className="form-control" onClick={() => this.handleSubmit} />
   </form>
});

It also looks like your form is uncontrolled, which another possibly is having the select change a value in state.

<select name="size" onChange={e => this.handleChange(e, i)} className="form-control" style={{height: '46px;'}}>
  <option key="1" value="1">Red</option>
  <option key="2" value="2">Yellow</option>
  <option key="3" value="3">Green</option>
</select>

and in your handleChange, you would change a value in state that would correspond to the product from your state.

You can use a ref to get form values from the DOM.

Here you need one ref per product, so you could use the index of product to save the ref and also to submit de form.

class Example extends Component {
  constructor(props) {
    super(props);
    this.state = {
      products: [],
    };

    this.selectByProduct = {};
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event, productIndex) {
    event.preventDefault();
    const size = this.selectByProduct[productIndex].value;
    console.log(`you submitted the size ${size} of product ${productIndex}`)
  }

  render() {
    return this.state.products.map((product, i) => (
      <form onSubmit={event => this.handleSubmit(event, i)}>
          <select ref={select => this.selectByProduct[i] = select} name="size" className="form-control" style={{height: '46px;'}}>
            <option key="1" value="1">Red</option>
            <option key="2" value="2">Yellow</option>
            <option key="3" value="3">Green</option>
          </select>
          <input type="submit" value="Pick This" className="form-control" />
      </form>
    ));
  }
}
Related