Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React statics with ES6 classes

Does the statics object work with ES6 classes in React?

class SomeComponent extends React.Component {    render() {     // ...   }  }  React.statics = {   someMethod: function() {     //...   } }; 

Something like the above gives me undefined method someMethod when I do SomeComponent.someMethod()

like image 709
niftygrifty Avatar asked Apr 03 '15 13:04

niftygrifty


People also ask

Does the statics object work with ES6 Classes in React?

statics only works with React. createClass . Simply declare the method as a static class method: class SomeComponent extends React.

What is ES6 Classes in React?

ES6 introduced classes. A class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class , and the properties are assigned inside a constructor() method.

Can you use JavaScript Classes in React?

So what are my recommendations for React components? You can use class in your JS if you don't inherit twice and don't use super. Prefer to write React components as pure functions when possible. Use ES6 classes for components if you need the state or lifecycle hooks.

Does Reactjs use ES6?

React uses ES6, and you should be familiar with some of the new features like: Classes. Arrow Functions. Variables (let, const, var)


2 Answers

statics only works with React.createClass. Simply declare the method as a static class method:

class SomeComponent extends React.Component {    static someMethod() {     //...   }    render() {     // ...   }  } 

Regarding

React.statics = { ... } 

You are literally creating a statics property on the React object. That property does not magically extend your component.

like image 173
Felix Kling Avatar answered Sep 20 '22 13:09

Felix Kling


Although statics only works for React.createClass, you can still write static methods in ES6 notation. If you are using ES7, then you can also write static properties.

You can write statics inside ES6+ classes this way:

class Component extends React.Component {     static propTypes = {     ...     }      static someMethod(){     } } 

Or outside the class like this:

class Component extends React.Component {    .... }  Component.propTypes = {...} Component.someMethod = function(){....} 

If you want to write it like the former, then you have to set stage: 0 on Babel (since its experimental).

like image 33
Jonathan Huang Avatar answered Sep 18 '22 13:09

Jonathan Huang