homerboy homerboy - 26 days ago 6
React JSX Question

How to distinguish different form inputs in React?

I have two form inputs that I want to have for name and email.

enter image description here

I'm following examples from the React docs (https://facebook.github.io/react/docs/forms.html), but I'm not sure how I can distinguish between the two different forms. When I type in the first or second form, the other form receives

this.state.value
as well.

constructor(props) {
super(props);
this.state = {
value: '',
}
}

handleChange(e) {
this.setState({
value: e.target.value,
})
}

input() {
return (
<form>
<input type="text" value={this.state.value} onChange={this.handleChange.bind(this)}/>
<input type="email" value={this.state.value} onChange={this.handleChange.bind(this)}/>
</form>
)
}


I'm using ES6. Do I need some sort of
id
to distinguish between the two forms? I tried to have a different value in the constructor (i.e.
email = ''
) but it yielded the same results.

Answer
constructor(props) {
  super(props);
  this.state = {
    textValue: '',
    emailValue: ''
  }
}

handleTextChange(e) {
  this.setState({
    textValue: e.target.value
  })
}

handleEmailChange(e) {
  this.setState({
    emailValue: e.target.value
  })
}

input() {
  return (
    <form>
      <input type="text" value={this.state.textValue} onChange={this.handleTextChange.bind(this)}/>
      <input type="email" value={this.state.emailValue} onChange={this.handleEmailChange.bind(this)}/>
    </form>
  )
}
Comments