0

I'm new to React. It might be more JS question than React question tho. When I write the code in three different ways for this part, they all work fine showing "ID is 1" in the console.

1

<Post click={() => this.postSelectedHandler(post.id)}/>

2

<Post click={() => {this.postSelectedHandler(post.id)}}/>

3

<Post click={() => {return this.postSelectedHandler(post.id)}}/>

My question is why they all work fine. Especially #3 returns the function and I don't understand why it works in the same way as the other two. About #1 & #2, with or without {} doesn't matter?

original code (same as #1)

  postSelectedHandler = id => {
    console.log("ID is " + id);
  };

  render() {
    const posts = this.state.posts.map(post => {
      return (
        <Post click={() => this.postSelectedHandler(post.id)}/>
      );
    });

    
    return (
      <div>
        <section>{posts}</section>
      </div>
    );
  }

Thank you for your help.

Community
  • 1
  • 1
Yuka
  • 1
  • The three should be equivalent in this case. arrow function syntax allows for `() => { return fn(); }` the curly brackets mean you can use multiple lines but you don't have to. This is the same as `() => fn()` it's shorter and without curly brackets can only be a single expression but it also has an implicit return. Finally `() => { fn() }` uses the same rules as the first one but doesn't return anything explicitly just runs `fn()`. Which is fine for a click handler. – VLAZ Mar 15 '20 at 07:42
  • Also relevant: [Arrow function without curly braces](https://stackoverflow.com/questions/39629962/arrow-function-without-curly-braces) – VLAZ Mar 15 '20 at 07:46
  • That's a common question, you may refer my summary here https://github.com/ibarapascal/access-catalog/blob/master/blog/summary-of-react-develop-practice/summary-react.md/#function-binding-in-details – keikai Mar 15 '20 at 07:50
  • *If* the return value from a handler gets used, both 1 and 3 will return the value of `postSelectedHandler` to the caller. Pretty sure React doesn't process it nowadays, though it *used* to a long time ago, see https://stackoverflow.com/q/31191841 and https://github.com/reagent-project/reagent/issues/78. There's a non-zero chance of this behavior changing in the far future. – CertainPerformance Mar 15 '20 at 07:51

0 Answers0