writing function outside of a class in react component

esther Joo picture esther Joo · Dec 6, 2017 · Viewed 7.4k times · Source

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?

Answer

Dane picture Dane · Dec 6, 2017

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.