I am translating my React App with headless CMS. I have a language switcher in my navbar and on each component has to be the specified language.
The language Switcher logic:
const [selected, setSelected] = useState('en-us');
const handleEnglish = () => {
cookies.set('chosenLang', 'en-us');
setSelected('en-us');
};
<button onClick={handleEnglish}>EN</button>
const handleFrench = () => {
cookies.set('chosenLang', 'fr-fr');
setSelected('fr-fr');
};
<button onClick={handleFrench}>FR</button>
And logic in component based on which the language is recognised (pretty simple):
{lang: selected}
This works, but just because the language switcher is in the same file as translated component. Once I created separate component for navbar (where is the lang switch) it does not work and I don't know how to pass the state of it to other components)
I tried in my page component to do something like <Navbar {...selected} />
, how I would normally pass the props but no luck with that.
Just use the context API, the selected language state is available only locally in that component.
You can do like this:
https://codesandbox.io/s/languagecontext-example-t33pm
You can you context or redux, react-redux to share state between components across app.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.