Constant placement in a ReactJS component

When you want to define some constant values like style or image URLs then it's always better to define that outside of component. It will become global values and available inside each function/class of that file.

Another option of defining constants is on a class instance itself, but then that variable will be available only inside the class. It means if you defined two classes inside the same file, then one class variable would not be available inside another class.

Like this:

class ABC extends React.Component{
   constructor(){
      super();
      this.a = 10;
      this.b = 20;
   }

   render(){
      console.log(this.a, this.b);
      return (....);
   }
}

Note: React classes don't have the feature of class level properties; we can only define methods. But if you want to define values then you need to use class transform properties.


Create a constants.js for shared constant variables/objects and export it from there for better maintainability.

export const redPanda = {
  src: 'https://upload.wikimedia.org/wikipedia/commons/b/b2/Endangered_Red_Panda.jpg',
  alt: 'Red Panda',
  width: '200px',
};

import React from 'react';
import ReactDOM from 'react-dom';
import { redPanda } from 'path/to/your/constants/file'; //import from your constants.js

class RedPanda extends React.Component {
  render() {
    return (
      <div>
        <h1>Cute Red Panda</h1>
        <img src={redPanda.src} alt={redPanda.alt} width={redPanda.width} />
      </div>
    );
  }
}

ReactDOM.render(<RedPanda />, document.getElementById('app'));

Tags:

Reactjs