0

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?

1
  • Yes you would have to use state... Commented Nov 17, 2016 at 1:44

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

7 Comments

Since you beat me ;), if you needed a live demo, here's something I put together: jsfiddle.net/ow99x7d5
@AndrewLi Thanks for the edits. I modified the code to remove the (event) => this.valueChanged(event) since it can be resolved simply by binding this.valueChanged in the constructor. Feels a bit more idiomatic.
Thanks, very helpful. I was wondering if there is a way without using state, like using setProps(deprecated).
@ZackTanner Sure, no problem :-).
@NeoWang This would be the "react way" of doing it. I'd say any other way is a hack or ill-advised. Have a look at Thinking in React: facebook.github.io/react/docs/thinking-in-react.html
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.