I develop a component npm library that use 18next. the consumer of the library, also use 18next. we created instance for each and pass it down using the provider component.
for some reason the translations are always overriden by the consumer.
i tried the solution here
but when i removed .use(initReactI18Next) it corrupted the translation in the component and didn't help in the consumer with the initial issue. any other solution that might work ?
I18n.js file - in the components project:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
const resources = {
en: {
translation: require('./translations/messages_en.json'),
},
bg: {
translation: require('./translations/messages_bg.json'),
},
}
const widgetInstance = i18n.createInstance();
widgetInstance
// pass the i18n instance to react-i18next so the t function will be in the context.
.use(initReactI18next)
// init i18next
// for all options read: https://www.i18next.com/overview/configuration-options
.init({
resources,
react: {
useSuspense: false,
},
fallbackLng: 'en',
debug: true,
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
},
})
.then(result => result)
.catch(error => console.error(error));
export default widgetInstance;
the component using it:
import i18next from '../../../locale/i18next';
....
<I18nextProvider i18n={i18next}>
<div className="myComponent"/>
</ I18nextProvider i18n={i18next}>
i18n.js in the consumer of the components npm library:
import i18next from ‘i18next’;
import {initReactI18next} from “react-i18next”;
const newInstance1 = i18next.createInstance();
export default function i18n(locale: string) {
void newInstance1.use(initReactI18next)
.use({
type: ‘backend’,
read: (
language: string,
namespace: string,
callback: (
err: any | null,
translations?: Record<string, string>,
) => void,
) => {
return import(`./locales/messages_${locale}.json`)
.then(translation => {
callback(null, translation);
})
.catch(error => {
callback(error);
});
},
})
.init({
lng: locale,
fallbackLng: “en”,
keySeparator: false,
});
return newInstance1;
}
the component using it in the provider in the consumer:
import i18n from ‘../../i18n’;
<I18nextProvider i18n={i18n(locale)}>
<LibrayComponent {...props} />
</I18nextProvider>