The ‘this’ keyword typically references a JavaScript element depending on the scope or context of its use.

Let’s say we’ve a React component of a SignUp form & we need to create custom methods inside of our component for handling events. In the snippet below, we’re calling a custom method saveUser on submitting the form.

class SignUp extends React.Component {
      render() {
        return (
            <form className="signup-form" onSubmit={this.saveUser}>
                <h2>Register yourself</h2>
                <input
                    type="text"
                    required
                    placeholder="Name"
                />
                <input
                    type="email"
                    required
                    placeholder="Email Address"
                />
                <input
                    type="password"
                    required
                    placeholder="Password"
                />
                <button type="submit">Signup</button>
            </form>
        )
    }
}

But for custom methods in React, this is undefined and we’ve couple of options to make it work.

Constructor Way

constructor(props) {
    super(props);
    this.saveUser = this.saveUser.bind(this)
}

This is one option to bind this to your custom methods, but you’ll soon find yourself writing more lines of code and binding this to every single custom method in your component.

Make it a Property

Second option is to simply make it a property which is set to an arrow function.

saveUser = event => {
    event.preventDefault();
    console.log(this.Name);
}

You may also Like