This is mainly divided into two categories
- Class components
- Functional Components
Class components
Consider you have your code as follow:
getMovies(movieName){...}
render(){
<button onClick={/*Attach event here*/}>Get</button>
}
There can be 4 ways
- Using binding in the constructor, This is a recommended way of binding a method.
class Movie{
constructor(props){
super(props);
this.getMovies = this.getMovies.bind(this);
}
getMovies(movieName){ //your code }
render(){
<button onClick={this.getMovies('some_movie_name')}>Get</button>
}
}
- Using binding in the render method itself. In terms of performance, it's the same as the previous one. The first one is a little cleaner for me.
class Movie{
getMovies(movieName){ //your code }
render(){
<button onClick={this.getMovies.bind('some_movie_name')}>Get</button>
}
}
- Using arrow function syntax in render().
class Movie{
getMovies(movieName){ //your code }
render(){
<button onClick={()=>this.getMovies('some_movie_name')}>Get</button>
}
}
- Using the arrow function in classes. This will have an impact on overall performance. You can read more about this here.
class Movie{
getMovies = (movieName) => { //your code }
render(){
<button onClick={this.getMovies('some_movie_name')}>Get</button>
}
}
Function components
Consider you have your code as follow:
function getMovies(movieName){ //your code }
return(){
<button onClick={/*Attach event here*/}>Get</button>
}
- There aren't many variations for the function component. Using either an arrow or regular function expression to define a function.
function Movie(){
function getMovies(movieName){...} //or const getMovies = (movieName) => {...}
return(
<button onClick={()=>getMovies('some_movie_name')}>Get</button>
{/*
if not arguments
<button onClick={getMovies}>Get</button>
*/}
)
}