HungryBird
HungryBird

Reputation: 1147

Arrow function in React

I just went through some react code, I am a bit confused about this arrow function. I know drawer is the function name, open here is a parameter, what about () ? what does it use for? can someone explain it? Many thanks!

  drawer = open => () => {
    this.setState({
      test: open,
    });
  };

I can call this function by this.drawer(true)

Upvotes: 0

Views: 95

Answers (4)

Treycos
Treycos

Reputation: 7492

This is called a curried function.

It is the equivalent of the following code :

  drawer = (open) => () => {
    this.setState({
      test: open,
    });
  };

This function needs to be called twice in order to be executed :

drawer('something')();

The first call : drawer('something') will return another function that you only have to call once with the open value already set up for you.

It is usually used to preconfigure callback passed to component props :

<DrawerOpener setOpen={this.drawer(true)}/>

Your component DrawerOpener can then call props.setOpen() to trigger an open event will not being able to chage the open variable of the function.

Upvotes: 2

Eric
Eric

Reputation: 603

What you're seeing here is called currying, where one arrow function returns another arrow function. So in your example, the first function has the parameter open, it then returns a function that then accesses the first one's parameter by creating a closure.

Here's some more examples: https://scotch.io/tutorials/closures-and-currying-in-javascript

From the link above there's a really good example that illustrates what's happening here and how it can be used:

let greeting = function (a) {
return function (b) {
    return a + ' ' + b
    }
}

let hello = greeting('Hello')
let morning = greeting('Good morning')

hello('Austin') // returns Hello Austin
hello('Roy') // returns Hello Roy
morning('Austin') // returns Good morning Austin
morning('Roy') //returns Good Morning Roy

Upvotes: 1

Anton Bahurinsky
Anton Bahurinsky

Reputation: 456

You are actually declaring a function which returns another function. An old-school equivalent of your code would be:

drawer = function(open) {
  return function() {
    this.setState({
      test: open,
    });
  }
}

Note that if you use classic function instead of arrow functions, this won't reference your class instance without binding.

Upvotes: 2

Quentin
Quentin

Reputation: 944532

() indicates an empty arguments list.

drawer is a function that takes one argument (open). The return value is another function (which takes no arguments).

Upvotes: 0

Related Questions