Search code examples
javascriptreactjscomponentsstatereact-props

Passing state from one component to another with React language switch


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.


Solution

  • 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.