Seun LanLege Seun LanLege - 1 month ago 5
Javascript Question

How to handle multiple controlled inputs with react es6?

here's my fiddle

https://codepen.io/seunlanlege/pen/XjvgPJ?editors=0011

i have two inputs and i'm trying to use one method to handle the onChange event for any input field.

i've torn the internet apart looking for a solution but came up with nothing.

i'm using es6 please how do i go about this?

class Form extends React.Component {
`constructor(props) {
super(props);
this.state = {text:{
e:'hi',
c:''
}};
this.handleSubmit = this.handleSubmit.bind(this);
}`

`handleChange(event,property) {
const text = this.state.text;
text[property] = event.target.value;
this.setState({text});
}`

`handleSubmit(event) {
alert('Text field value is: ' + this.state.text.e);
}`

`render() {
return (
<div>
<div>{this.state.text.e}</div>
<input type="text"
placeholder="Hello!"
value={this.state.text.e}
onChange={this.handleChange.bind(this)} />
<input type="text"
placeholder="Hello!"
value={this.state.text.c}
onChange={this.handleChange.bind(this)} />
<button onClick={this.handleSubmit}>
Submit
</button>
</div>
);
}
}`

ReactDOM.render(
`<Form />`,
document.getElementById('root')
);

Answer

You have not passed the propert to the handeChange function. pass it like this.handleChange.bind(this, 'e') and also the order of receiving props is wrong, property will be the first argument and then the event and not the reverse.

Code:

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {text:{
      e:'hi',
      c:''
    }};
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(property, event) {
    console.log(event.target.value);
    const text = {...this.state.text};
      text[property] = event.target.value;
      this.setState({text: text});
  }

  handleSubmit(event) {
    alert('Text field value is: ' + this.state.text.e);
  }

  render() {
    return (
      <div>
        <div>{this.state.text.e}</div>
        <div>{this.state.text.c}</div>
        <input type="text"
          placeholder="Hello!"
          value={this.state.text.e}
          onChange={this.handleChange.bind(this, 'e')} />
        <input type="text"
          placeholder="Hello!"
          value={this.state.text.c}
          onChange={this.handleChange.bind(this, 'c')} />
        <button onClick={this.handleSubmit}>
          Submit
        </button>
      </div>
    );
  }
}

ReactDOM.render(
  <Form />,
  document.getElementById('root')
);

CodePen

Comments