Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing function outside of a class in react component

I've seen code like this

function abc(){
  return 'abc'
}
class MyComponent extends React.Component {
    static abc = abc;
    render() { return <h1>{this.abc}</h1>; }
}

where function abc is defined outside of a react class. I have no clue why the author did it that way, why can't just do it within the class?

like image 614
esther Joo Avatar asked Dec 06 '17 06:12

esther Joo


People also ask

Is it possible to use a class component in react?

With the addition of Hooks, Function components are now almost equivalent to Class components. The differences are so minor that you will probably never need to use a Class component in React. Even though Function components are preferred, there are no current plans on removing Class components from React.

What is a functional component in react?

Functional components are nothing new in React, however it was not possible before version 16.8.0 to create a stateful component with access to lifecycle hooks using only a function. Or was it? Call me a pedant (many people already do!) but when we talk about class components we are technically talking about components created by functions.

When is the constructor of a React component called?

If there is a constructor () function in your component, this function will be called when the component gets initiated. The constructor function is where you initiate the component's properties. In React, component properties should be kept in an object called state.

Do you write functions inside or outside of the component?

Functional Component: Write functions inside or outside the component? I often wrote functional components following a 'Class architecture' where all my function that concern the component are written inside of it like a method in a class. For example, I have here a function counterAsFloat that is related to the Counter component.


1 Answers

These are ES6 static methods and are not exclusive to React. They are members of the component class and not of instances of the component. They are not used extensively in React, but they can be useful. It is even mentioned in the React docs:

Sometimes it’s useful to define a static method on a React component. For example, Relay containers expose a static method getFragment to facilitate the composition of GraphQL fragments.

They can be used as common members of the Component, shared by all instances of it. To give you an idea, other static members of a React class are displayName and defaultProps.

Also see Static methods in React. As you can see, there aren't many cases where you would use a static method.

like image 142
Dane Avatar answered Nov 10 '22 08:11

Dane