Skip to content Skip to sidebar Skip to footer

How To Include A Text Input In A React Component With Its Value Specified?

I need to include a text input in a React component, with its initial value passed from the component's props: But the input i

Solution 1:

Have a look at the documentation on forms, specifically controlled components.

Your valueChanged() method, where the change event is handled, would do something like this:

valueChanged(event) {
  this.setState({
    value: event.target.value //set this.state.value to the input's value
  });
}

That means that yes, your input value would need to use state (this.state.value.) If you want this.state.value to be populated from this.props.value, you could do something like this in the constructor:

constructor(props) {
  super(props);
  this.state = {
    value: props.value //passed prop as initial value
  }
  this.valueChanged = this.valueChanged.bind(this);
}

The above will initially set this.state.value to the passed prop value's value. Then apply the value from state and the onChange handler to your <input>:

<input value={this.state.value} type="text" onChange={this.valueChanged} />

Since this.state.value is the current input value, and is updated every time that value is changed, it becomes input-able as expected.

Here's a fiddle (thanks, Andrew): http://jsfiddle.net/ow99x7d5/2


Post a Comment for "How To Include A Text Input In A React Component With Its Value Specified?"