NeoWang NeoWang - 1 year ago 93
Javascript Question

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?

Answer Source

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) {
    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) {
  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):

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download