Suppose We have 3 functions in React –
function() { console.log('click'); }
function double(n1){ return n1 * 7;}
function multTwo(n1, n2) {return n1 * n2;}
You can convert these 3 function into arrow function with these 3 steps easily –
1- Remove function keyword along with the function name & add arrow
When you will remove the function keyword & name than all the above 3 functions will become like –
() { console.log('click'); }
(n1){ return n1 * 7;}
(n1, n2) {return n1 * n2;}
When you add the arrow , than all three function become like –
() => { console.log('click'); }
(n1) => { return n1 * 7;}
(n1, n2) => {return n1 * n2;}
2 – Removal of Parenthesis on left side
You only have to remove parenthesis , when single argument is passing in function , otherwise it’s not required. In above all these 3 functions , only in 2nd function we have single argument , so only you have to remove parenthesis in second function.
() => { console.log('click'); }
n1 => { return n1 * 7;}
(n1, n2) => {return n1 * n2;}
3- Remove “return”with curly braces on right side , can include parenthesis if expression is large
When you remove “return” & curly braces , than all function will be like –
() => console.log('click')
n1 => n1 * 7
(n1, n2) => n1 * n2
When you include parenthesis in last two expression than it will be like –
() => console.log('click')
n1 => (n1 * 7)
(n1, n2) => (n1 * n2)
Congratulations ! you successfully converted a function into arrow function in React.