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:
- Create a getter method in the class for getting the constant when required.
- 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:


… [Trackback]
[…] Find More here to that Topic: geeksforgeeks.org/how-to-declare-constant-in-react-class-2/ […]