NeoWang
NeoWang

Reputation: 18513

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:

 <input value={this.props.value} type='text'/>

But the input is not editable, and React complains:

 Warning: Failed form propType: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field.

So I add a onChange event handler:

 <input value={this.props.value} type='text' onChange={this.valueChanged} />

What should I do in the valueChanged handler to update the input value? Do I have to use state?

Upvotes: 0

Views: 3158

Answers (1)

Zack Tanner
Zack Tanner

Reputation: 2590

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

Upvotes: 5

Related Questions