Solution
To declare const array in react js, use const
keyword to define constant array, and import anyware you want to use.
const
The const
declaration creates block-scoped constants, much like variables declared using the let
keyword. The value of a constant can’t be changed through reassignment.
Snippet
In this snippet, we will create an array and as constant and console it in logs.
const arr = ["aGuideHub", "SortoutCode", "ReactJsSnippet", "Infinitbility"];
console.log(arr); // (4) ['aGuideHub', 'SortoutCode', 'ReactJsSnippet', 'Infinitbility']
Example
In this example, we will create const array in constants file and import in App.js
and show in the UI.
Let’s start coding…
Constants.js
export const Domains = [
"aGuideHub",
"SortoutCode",
"ReactJsSnippet",
"Infinitbility"
];
App.js
import React, { useEffect, useState } from "react";
import { Domains } from "./Constants";
export default function App() {
const [arr, setArr] = useState(Domains);
useEffect(() => {
console.log(arr);
}, []);
return (
<div className="App">
<h1>{`Constants Array`}</h1>
<p>{JSON.stringify(arr)}</p>
</div>
);
}
Output