Skip to content
Related Articles

Related Articles

How to declare constant in react class ?
  • Difficulty Level : Hard
  • Last Updated : 14 Dec, 2020

To declare a constant that can be accessed in a React class component, there are multiple approaches that could be efficiently implemented such that that constant is accessible class-wide. Constants can be declared in the following two ways:

  1. Create a getter method in the class for getting the constant when required.
  2. Assign the class constant after the declaration of the class. 

Create a sample project with the following command:

// constantDemo is the name of our folder
npx create-react-app constantDemo

Now move to the constantDemo folder using the following command:

cd constantDemo

The Project Structure will look like the following:



Filename: App.js Now open the App.js file and paste the following code in it:

Javascript




import React, { Component } from "react";
  
class App extends Component {
  
    static get myConstant() {
        return {
            name : "GFG",
            id : 1
        }
    }
  
    render() {
        return (
            <div>My constant is : 
{JSON.stringify(this.constructor.myConstant)}</div>
        );
    }
}
  
export default App

Now run the project using the following command:

npm start

Output : 

Another way of declaring the constants is shown below. Paste down the following code in the App.js file.

Filename: App.js

Javascript




import React, { Component } from "react";
  
class App extends Component {
  render() {
    return (
       <div>My constant is : 
{JSON.stringify(this.constructor.myConstant)}</div>
    );
  }
}
  
GFG.myConstant = {
    name : "GeeksForGeeks",
    id : 2
}
  
export default App

Now run the project using the following command:

npm start

Output:

react-js-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :