eszterkv / eszter.space

https://eszter.space
0 stars 0 forks source link

post: i18n for gatsby with hooks #18

Open eszterkv opened 4 years ago

eszterkv commented 4 years ago

structure:

src/
  i18n/
    en.json
    hu.json
  hooks/
    use-i18n.js

use-i18n.js

export default function useI18n() {
  const i18n = { hu, en };
  const defaultLang = 'hu';
  const [lang, setLang] = useState(defaultLang);

  function t(string) {
    const keys = string.split('.');

    try {
      let value = i18n[lang];
      while (typeof value !== 'string') value = value[keys.shift()];

      return value;
    } catch (error) {
      return string;
    }
  }

  return { t, lang, setLang };
}
eszterkv commented 4 years ago

needs context