Search code examples
reactjsstaticconstantsinstance-methods

How do you access React statics within instance methods?


I'm using React 16.13.0. I have defined this static block within my component ...

class FormContainer extends Component {
  statics: {
    DEFAULT_COUNTRY: 484;
  }

  constructor(props) {
    super(props);

    ...

  componentDidMount() {
    let initialCountries = [];
    let initialProvinces = [];
    // Get initial countries
    fetch('/countries/')
        .then(response => {
            return response.json();
        }).then(data => {
        initialCountries = data.map((country) => {
            return country
        });
        console.log("output ...");
        console.log(initialCountries);
        this.setState({
            countries: initialCountries,
        });
    });
    // Get initial provinces (states)
    console.log("val:" + this.DEFAULT_COUNTRY); 

My question is, how do I reference that static block? The above

console.log("val:" + this.DEFAULT_COUNTRY);

produces

undefined 

Solution

  • Confusion comes from old React.createClass function that you would use if your runtime didn't support classes as a Javascript feature. You would pass an object in React.createClass and React would create sort-of-a-class for that component. There, statics property on that object would serve like an object with all static properties of that pseudo class:

    // old
    const MyComponent = React.createClass({
      statics: {
        DEFAULT_COUNTRY: 484
      },
      render: function() {}
    })
    

    There is no real class going on here, it's just an object inside an object, and it is indeed easy to confuse with e.g. static block in Java

    With ES6 classes (which you are using) static properties are declared like this

    class MyComponent extends React.Component {
      static DEFAULT_COUNTRY = 484
      static ANOTHER_STATIC_PROPERTY = 23
    
      render () {}
    }
    

    And can be accessed as MyComponent.DEFAULT_COUNTRY anywhere

    You are most likely using Babel, in that case, babel-plugin-proposal-class-properties should be enabled, as not all browsers support this feature. Node without Babel supports class properties from version 12

    There are no static blocks in Javascript per se, but you can modify the class from static context from outside, e.g.

    class MyComponent extends React.Component {
      static DEFAULT_COUNTRY = 484
      static ANOTHER_STATIC_PROPERTY = 23
    
      render () {}
    }
    
    MyComponent.HELLO = 'world'