Thursday, May 14, 2026
HomeLanguagesJavascriptHow to declare constant in react class ?

How to declare constant in react class ?

To declare a constant that can be accessed in a React class component, there are multiple approaches that could be efficiently implemented such 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:

RELATED ARTICLES

Most Popular

Dominic
32514 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6892 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12107 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6975 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS