Thursday, November 28, 2024
Google search engine
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

Recent Comments