Tuesday, November 18, 2025
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

1 COMMENT

Most Popular

Dominic
32402 POSTS0 COMMENTS
Milvus
95 POSTS0 COMMENTS
Nango Kala
6772 POSTS0 COMMENTS
Nicole Veronica
11921 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11992 POSTS0 COMMENTS
Shaida Kate Naidoo
6899 POSTS0 COMMENTS
Ted Musemwa
7156 POSTS0 COMMENTS
Thapelo Manthata
6853 POSTS0 COMMENTS
Umr Jansen
6845 POSTS0 COMMENTS