DrivingInsanee
DrivingInsanee

Reputation: 1691

reactjs input value does not change (with defaultValue)

I have a simple reactjs which has inputs in it. One of those inputs is set as such:

<input type='text' name='name' defaultValue='default' />

When I submit the form, I prevent default, and pass the event.target to a function that serializes the data in the form.

But, when I pass the form as an element, the input inside always retains its defaultValue.

Any ideas?

Upvotes: 1

Views: 2813

Answers (1)

janpieter_z
janpieter_z

Reputation: 1742

By default a component isn't 'controlled'. This means the value will stay the same on every render. The default value actually stays the same until you're handling the changes to the input in your component.

To make use of React's Controlled Components you should supply a value and an onChange handler. An example copied from React's documentation below.

  getInitialState: function() {
    return {value: 'Hello!'};
  },

  handleChange: function(event) {
    this.setState({value: event.target.value});
  },

  render: function() {
    return (
      <input
        type="text"
        defaultValue="default"
        value={this.state.value}
        onChange={this.handleChange}
      />
    );
  }

Upvotes: 5

Related Questions