Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an input field with onBlur and a value from state blocks input in Reactjs JSX?

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>
like image 207
Stefan Bookholt Avatar asked May 20 '15 09:05

Stefan Bookholt


1 Answers

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.

like image 75
Anders Ekdahl Avatar answered Sep 23 '22 15:09

Anders Ekdahl