Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React function not displayed in "this" but yet still callable

I am confused as to how React functions bind to this.

import React, { Component } from 'react';

class App extends Component {
  randomFunction(){
    console.log("Hello World")
  }

  render() {
    return (
      <div>
        {console.log(this)}
        {console.log(this.randomFunction)}
      </div>
    );
  }
}

export default App;

You should see on the console both of these return something, however randomFunction is not present in the previous this object. As show in the image below

enter image description here

I am curious to know how/where this link is made?

like image 744
William Avatar asked Jan 27 '18 16:01

William


People also ask

How do you call a React hook inside a function?

Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders.

How do I call a nested function in React JS?

You can call it using function2() in ES6 .

How do you pass a function from one component to another in React hooks?

With React, typically you only need to bind the methods you pass to other components. For example, <button onClick={this.handleClick}> passes this.handleClick so you want to bind it. However, it is unnecessary to bind the render method or the lifecycle methods: we don't pass them to other components.


1 Answers

That's because your function is moved to the prototype. This way it is created only once, not per every component instance.

You can verify this by calling console.log(this.__proto__) or expanding __proto__ object visible on your screenshot.

like image 148
pwolaq Avatar answered Oct 18 '22 07:10

pwolaq