I have a react project "App" that requires another package "AppComponents" which in turn requires "UI" package.
App (has Intlprovider) => AppComponents (useIntl works) => UI (useIntl does not work)
I added the Intl Provider in "App", and when I use the hook "useIntl" in "AppComponents" package, it works fine. But when I use that hook in the "UI" package, it doesn't work, saying there's no provider:
Uncaught Error: [React Intl] Could not find required
intl
object. needs to exist in the component ancestry.
I'm using:
react-intl v6.0.4
react v18.0.0
node v18.0.0
npm v8.6.0
"App":
import { useMemo, useState, createContext } from 'react';
import { IntlProvider } from 'react-intl';
import { ReactNode } from 'react';
import { MessageFormatElement } from 'react-intl';
export type TTranslationData = Record<string, string> | Record<string, MessageFormatElement[]>;
export interface II18nContext {
locale: string;
setLocale: (newLocale: string) => void;
setTranslation: (data: TTranslationData) => void;
}
export interface II18nProviderProps {
children: ReactNode;
}
const I18nContext = createContext<II18nContext | null>(null);
function I18nProvider({ children }: II18nProviderProps) {
const [locale, setLocale] = useState(navigator.language);
const [message, setMessage] = useState<TTranslationData | Record<string, never>>({});
const value = useMemo(
() => ({
locale,
setLocale,
setTranslation: (data: TTranslationData) => setMessage(data),
}),
[locale],
);
return (
<I18nContext.Provider value={value}>
<IntlProvider locale={locale} messages={message}>
<App />
</IntlProvider>
</I18nContext.Provider>
);
}
"UI" package (not working):
import { useIntl } from 'react-intl';
...
function Searchbar(props: SearchbarProps) {
const intl = useIntl();
...
return (
...
{intl.formatMessage({
id: 'searchbar.placeholder',
description: 'React UI search bar placeholder',
defaultMessage: 'Search',
})}
...
);
...
}
Any help would be much appreciated.