Using arrow function in React JS - Bind

Using arrow function in React JS - Bind

When programming applications with React Js to handle events you need to use the bind method. There are many different ways you can do that, such as placing it in a constructor

1
2
3
4
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}

Or you can also call it in the render function but this way will likely degrade your application performance, but in most cases it is negligible.

1
2
3
4
5
6
7
render() {
return (
<button onClick={this.handleClick.bind(this)}>
Click me
</button>
);
}

However there is another way to make your code more concise and readable by using the arrow function

1
2
3
4
5
6
7
8
9
10
11
handleClick = () => {
// handling event here
}

render() {
return (
<button onClick={this.handleClick}>
Click me
</button>
);
}

P/S: This method also helps to optimize the performance of your application similar to the use of bind in constructor.

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×