Which is the correct way to define globals values for labels in React?

55 Views Asked by At

im trying to search how to define a dictionary of labels values for use in all the pages of my React app, i dont know which is the correct way or the best practice for that.

Im thinking something like to define a json with key-values:

const MyDictionaryEN:{
    NameHomePage: "Home page",
    LabelName:    "Name"
}
export default MyDictionaryEN;

And in each component only import the json file and reference the value:

import MyDictionaryEN from "./MyDictionaryEN.json"

 function MyPage() {
   return (
    <div>{MyDictionaryEN.NameHomePage}</div>
   )
 }

is this correct or exist a better way?

1

There are 1 best solutions below

0
Abbas Bagheri On

Other way to using of global variables (or object) is add your variable in window object! for example :

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

import App from "./App";

window.MyDictionaryEN = {
  NameHomePage: "Home page",
  LabelName: "Name"
};

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

then I am able to access it in every component:

import "./styles.css";

export default function App() {
  console.log(window.MyDictionaryEN);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

I'm not sure it is best option but you can use it aside of other options.