11

I've made a small fiddle to show the problem: http://jsfiddle.net/4TpnG/582/ When you have an input box with onBlur attached to it, and an initial value from state, input from the keyboard is blocked. When onChange is attached, it's working correctly. Why is this happening and how can this be solved? I would have expected it to accept the characters you type and update the state onBlur.

var Test = React.createClass({

      getInitialState: function() {
        return {
          value: "hallo"
        };
      },

      render: function() {
          return ( < form >
            < div >
            Onchange: < input type = "text"
            value = {
              this.state.value
            }
            onChange = {
              this.handleChange
            }
            /><br/ >
            Onblur: < input type = "text"
            value = {
              this.state.value
            }
            onBlur = {
              this.handleChange
            }
            />
      </div >
            < /form>
    );
  },
  handleChange: function(e){
      this.setState({value: e.target.value});
  }
});

React.renderComponent(<Test/ > , document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.12.2/react-with-addons.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.12.2/JSXTransformer.js"></script>

1 Answer 1

9

The value attribute ties the value of the input to that state, and if the user changes the value then the state and the input value is no longer tied to each other. So React stops that from happening.

You probably want to use the defaultValue attribute instead.

If you want to use the value attribute you need the onChange to sync it with the component state. This because the component can re-render at any time, and if the value is out of sync with the state that would render an old value.

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

2 Comments

Cool thanks! It works with the 'defaultValue' attribute, that is probably what you meant.
Ah, sorry, I'm on mobile and didn't look that up, I'll change the answer.

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.