Search code examples
javascriptreactjs-flux

React onChange event does not fire


The issue is onChange event does not fire in the input tag. I was using LinkedStateMixin to track input value before. Lately, I want to add onChange event to run some function then I removed LinkedStateMixin, but the onChange cannot fire. I tried to add e.stopPropagation() to setUsername(), but it is not working too. I tried other event such as onKeyDown, onClick, and ect. none of them can be fired. What is the problem?

var React = require('react');

var SessionActions = require('../../actions/session_actions');
var UserStore = require('../../stores/user_store');

var LogInForm = React.createClass({

  getInitialState: function() {
    return ({
      user: undefined,
      username: '',
      password: '',
    });
  },

  componentDidMount: function() {
    this.token = UserStore.addListener(this.updateUserStore);
  },

  componentWillUnmount: function() {
    this.token.remove();
  },

  updateUserStore: function() {
    this.setState({user: UserStore.all()});
    this.setState({username: ''});
    this.setState({password: ''});
  },

  setUsername: function(e) {
    console.log("Fired");
  },

  handleSubmit: function(e) {
    e.preventDefault();
    SessionActions.logIn({
      username: this.state.username,
      password: this.state.password
    });
    this.updateUserStore();
  },

  render: function() {
    return (
      <div>
        <h4>Log In</h4>
        <div> </div>
        <form onSubmit={this.handleSubmit}>
          <input onChange={this.setUsername} placeholder="Username" type="text"/>

          <input placeholder="Password" type="password"/>

          <input type="submit" value="Log In"/>
        </form>
      </div>

    );
  }
});

module.exports = LogInForm;

Solution

  • Change the function name from setUsername to handleUsername.