I'm not so good with arrow functions and would like some practice changing from arrow function to regular function. This is within React.
function render() {
const todoItems = this.state.todos.map(
item => <TodoItem
key={item.id}
item={item}
handleChange={this.handleChange}
/>
);
There are a few general forms of arrow functions.
arg1 => is strictly for one argument(arg1, arg2) => more than one argument, enclose in parentheses.() => no arguments also requires parenthesesOn the other side of the arrow, there are another 2 forms:
=> value returns value (or the result of an expression)=> {someStatements;} does not implicitly return anything.function()When converting to functions, follow this table:
arg1 => becomes function(arg1)(arg1, arg2) => becomes function(arg1, arg2)=> value becomes function(args) { return value }=> { someStatements;} becomes function(args) { someStatements;}this: different for arrow functionsLastly, a subtle but important difference. Arrow functions use this from their wrappers. Functions declared with function keyword always have their own this.
So in this particular case, given todos.map(item => <Component />), the function is item => <Component /> and working backwards from the table above we can see that this is equivalent to the function function(item) { return <Component />; }
The full line looks like this:
const outerThis = this; //save with a different name so we can access within function
const todoItems = this.state.todos.map(
function(item) {
return <TodoItem key={item.id} item={item} handleChange={outerThis.handleChange}/>
}
)
See also Arrow Function Expression on MDN, where you can read about a few other arrow function caveats (like no arguments, new, prototype or yield) and this operator.
If you want transform an arrow function to regular function, follow this code:
const todoItems = this.state.todos.map(handleMap)
function handleMap(item) {
return <TodoItem key={item.id} item={item} handleChange={this.handleChange}/>
}
But, I recommend to use function components and React hooks. Read this artice: https://reactjs.org/docs/hooks-intro.html