Responsive form component to submit handler not working

I have the following React component:

class Form extends React.Component { handleSubmit(e) { e.preventDefault(); let loginInput = ReactDOM.findDOMNode(this.refs.login); // change Main component state this.props.addCard(loginInput.value); // reset the form loginInput.value = ''; } render() { return( <form onSubmit={this.handleSubmit}> <input placeholder="githug login" ref="login" /> <button>Add Login</button> </form> ); } } 

As you can see, I want the handleSubmit function to handleSubmit called whenever the form is submitted. I indicated this by adding a function to the onSubmit handler.

The function is called at the right time. However, the value of this inside this function is null . This is surprising to me, as I expected this be a component of React. The fact that this is null surprises me because I use very similar logic / code offered by the official documentation.

I would appreciate help in figuring out why this not a React component, as expected, and how to fix the code so that it is.

+6
source share
1 answer

When you use React with ES2015 classes , you must set this to event handlers

 class Form extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(e) { e.preventDefault(); let loginInput = this.refs.login; this.props.addCard(loginInput.value); loginInput.value = ''; } render() { return( <form onSubmit={ this.handleSubmit }> <input placeholder="githug login" ref="login" /> <button>Add Login</button> </form> ); } } 

Example

No Autobinding

The methods follow the same semantics as regular ES6 classes, which means that they do not automatically associate this with the instance. You will have to explicitly use .bind (this) or the arrow functions =>.

+13
source

All Articles