-1
const handleChange = name => event => { setState({ ...state, [name]: event.target.checked }); }; 

See the complete code at CodeSandbox.

2
  • it means a function that returns a function. Commented Dec 17, 2019 at 2:41
  • Can I use only one arrow function to receive the parameters "name" and "event" at the same time, and if so, what should I do. Commented Dec 17, 2019 at 3:10

2 Answers 2

3

argumentName => returnValue is shorthand for (argumentName) => {return returnValue;}

So, your code is equivalent to

const handleChange = (name) => { return (event) => { setState({...state, [name]: event.target.checked}); } } 

In other words, handleChange is a function which itself returns another function, and that inner function does the setState() call.

If you did this:

const foo = handleChange("Bar"); 

The value of foo would essentially be this (a function):

foo = (event) => { setState({...state, "Bar": event.target.checked}); } 

Edit: one thing I'll note is that it could be useful to rename handleChange to something that more accurately describes what it does. For instance:

const createHandleOnChangeFunction = name => event => { setState({ ...state, [name]: event.target.checked }); }; 

Now it's a little more clear what this function does... it creates a function that handles onChange events.

Sign up to request clarification or add additional context in comments.

Comments

0

a function that returns a function.

It's like a function factory... where you can build a function where it has ( in this case name ) things preset in the function.

Very common in functional programming.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.