I have a Gatsby website that is using react-intl. I am successfully able to switch languages. Currently the <IntlProvider> is defined in layout.js, like so:
const Layout = ({ children }) => {
return (
<StaticQuery
query={graphql`
query LayoutQuery {
site {
siteMetadata {
languages {
defaultLangKey
langs
}
}
}
}
`}
render={data => {
const url = globalHistory.location.pathname;
const { langs, defaultLangKey } = data.site.siteMetadata.languages;
const langKey = getCurrentLangKey(langs, defaultLangKey, url);
const homeLink = `/${langKey}/`;
const langsMenu = getLangs(langs, langKey, getUrlForLang(homeLink, url))
let showLanguageSelect = true;
let onHomePage = true;
showLanguageSelect = url === '/404/' ? showLanguageSelect = false : showLanguageSelect = true;
onHomePage = url === '/en/' || url === '/fr/' ? onHomePage = true : onHomePage = false;
return (
<IntlProvider
locale={langKey}
messages={i18nMessages[langKey]}
>
<div>
<Header langs={langsMenu} homeLink={homeLink} showLanguageSelect={showLanguageSelect} homeHeader={onHomePage} />
<div>
{children}
</div>
{showLanguageSelect && <Footer langs={langsMenu} homeLink={homeLink}/>}
</div>
</IntlProvider>
)
}}
/>
);
};
However this provider doesn't pass props to all children in the same way React context would. Trying to use the following code from a component I don't explicitly pass the langKey to results in an error:
import { useIntl } from 'react-intl';
const MyComponent: FC = () => {
const intl = useIntl()
return <div>{`Current locale: ${intl.locale}`}</div>
}
export default MyComponent
"[React Intl] Could not find required intl object. needs to exist in the component ancestry."
Ideally I'd like to have langKey available as global context. How could I do this?