0

We are making an npm react package (by tsdx library), a custom hook for multi-languaging react projects. Developers who install this package need to make a config.json file at the root and a Languages.json file in the public folder of their Next.js project. What we need is that we can read Languages.json on the client-side of the app.

Package files: LanguageProvider.tsx: A react context that stores the current locale state.

UseTranslation.tsx: A custom hook that gets the locale from the context and finds the key from the same locale in Languages.json.

export function useTranslation() {
  const { locale } = useContext(LanguageContext);
  let LanguagesFile;
  if (typeof window === 'undefined') {
    const fs = require('fs');
    LanguagesFile = fs.readFileSync("./public/Languages.json", 'utf8');
  }
  
  function t(key: string) {
    if (typeof LanguagesFile !== 'undefined') {
      const Languages = JSON.parse(LanguagesFile);
      if (!Languages && !Languages[locale] && !Languages[locale][key]) {
        console.warn(`No string '${key}' for locale '${locale}'`);
        return false;
      } else {
        return Languages[locale][key].toString() || '';
      }
    }
  }
  return t;
}

When I log Languages.json file from UseTranslation.tsx, it shows me the data on the server, but it is undefined on the client-side of the app.

  • Why not store the languages as object instead json, and then regular `import` instead of `fs.readFileSync`? – Hagai Harari Oct 11 '21 at 13:34
  • Isn't this the same problem as [Warning: Did not expect server HTML to contain the text node "Home" in
    ](https://stackoverflow.com/questions/69515500/warning-did-not-expect-server-html-to-contain-the-text-node-home-in-div)?
    – juliomalves Oct 11 '21 at 15:11

0 Answers0