Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  5] [ 4]  / answers: 1 / hits: 90733  / 7 Years ago, fri, july 14, 2017, 12:00:00

I'm a beginner in React, and I'm a little confused about calling a function in React.



I saw the following ways and I don't know when to use each and which one.




  • handleAddTodo ={this.handleAddTodo}

  • handleAddTodo ={this.handleAddTodo()}

  • handleAddTodo ={handleAddTodo}

  • handleAddTodo ={this.handleAddTodo}

  • handleAddTodo ={handleAddTodo()}



Are these interchangeable? Could I do that to handle an event, the same way to call a function?


More From » reactjs

 Answers
19

Are these interchangeable?




Short answer: No.






Let's take a look at the different snippets you've posted:






someFunction() vs someFunction



With the former syntax, you are actually invoking that function. The latter is just a reference to that function. So when do we use which?




  • You would use someFunction() when you want that function invoked and its result returned immediately. In React, this is typically seen when you split parts of your JSX code to a separate function; either for reasons of readability or reusability. For example:



    render() {
    myFunction() {
    return <p>Foo Bar</p>;
    }
    return (
    <div>
    {myFunction()}
    </div>
    );
    }







  • You would use someFunction when you want only to pass the reference to that function to something else. In React, this is usually an event handler that is passed down to another child-component via props so that that component can call the event handler when it needs to. For example:



    class myApp extends React.Component {
    doSomething() {
    console.log(button clicked!);
    }
    render() {
    return (
    <div>
    <Button someFunction={this.doSomething} />
    </div>
    );
    }
    }

    class Button extends React.Component {
    render() {
    return (
    <button onClick={this.props.someFunction}>Click me</button>
    );
    }
    }






someFunction() vs this.someFunction()



This has to do with the context of the function. Basically, where is this function?. Is part of the current Component, then use this.someFunction(), is it part of the parent Component passed in as props, then use this.props.someFunction(). Is it a function inside the current method, then just use someFunction().



Obviously, there's a lot more to it than that, but it's the best basic summary I can give.



For a better understanding, have a read here. It is a great guide to how the this keyword works in Javascript and in React in particular.


[#57080] Wednesday, July 12, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
eliasf

Total Points: 703
Total Questions: 97
Total Answers: 129

Location: Chad
Member since Tue, Apr 27, 2021
3 Years ago
;