1

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?

1 Answer 1

5

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}
      />
    );
  }
Sign up to request clarification or add additional context in comments.

Comments

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.