1

Consider the following example:

const foo = string => "bar" + string;

class Example extends React.Component {
  foo = string => "bar" + string
  
  render = () => <p>
    {foo("asd"); this.foo("asd")}
  </p>
}

The only thing that I thought about is that a function inside the component's body can access it's attributes such as props, state, and anything inside the body including functions, but we can pass them as the outer function's parameters as well. So is this the only "advantage or disadvantage" of this, or there's something more advanced?

Gergő Horváth
  • 3,195
  • 4
  • 28
  • 64
  • 2
    If the function uses `this` to access your components properties/methods then yes it should be part of the component. Otherwise, no it doesn't really matter. – kemicofa ghost Jan 20 '19 at 13:36
  • 3
    Possible duplicate of https://stackoverflow.com/questions/155609/whats-the-difference-between-a-method-and-a-function – Mirakurun Jan 20 '19 at 13:37
  • If you put that code inside the `class`, it actually becomes part of the constructor. That's not what you'd want if you are not working with an instance. – Bergi Jan 20 '19 at 13:44
  • Possible duplicate of https://stackoverflow.com/questions/42645297/function-inside-render-and-class-in-reactjs – Monica Acha Jan 20 '19 at 13:49
  • Possible duplicate of [What's the difference between a method and a function?](https://stackoverflow.com/questions/155609/whats-the-difference-between-a-method-and-a-function) – Reactgular Jan 20 '19 at 13:54
  • JS is a prototype language that uses functions. The issue here is that `class` is misleading if you come from another OOP language. You can use an external function as if it was a member function by doing `foo.bind(this)()`. So in JS there aren't really *classes* but we have the class syntax for convenience, because managing the value of `this` is a pain. – Reactgular Jan 20 '19 at 14:02

1 Answers1

3

In the case of React Native, declaring a function outside of the class is like making a static function. If you place the function in the class, it will be created for each instance of the class which in this case would be unnecessary.

In your example, I would consider whether foo() should only be used within that file or within other files as well. In the case of the latter, make a separate folder called utils/, put the function in there and import it where you need it.

When it comes to props, you could create the function outside of the class and invoke it with call() and would then have access to props:

foo.call(this);

const foo = () => console.log(this.props);

Joshua Obritsch
  • 1,253
  • 8
  • 14