Skip to content
Advertisement

How to use useState to display a different language

I’m trying to do a function using useState to change the languages of my website. However, I’m having an issue thinking about the logic of how can it be done since I’m newbie.

1st question: How can I use the function “handleLanguage” to change the menu language when I click in <li>.

2nd question: Which would be the best way to change the whole language website by clicking on the option? Because as I see, now if I click, will change only one component.

Code:

JavaScript

Advertisement

Answer

How can I use the function “handleLanguage” to change the menu language when I click in?

I would convert handleLanguage into a curried function to enclose a language value when attaching as a callback to select a language.

JavaScript

Which would be the best way to change the whole language website by clicking on the option? Because as I see, now if I click, will change only one component.

For this you will likely need to Lift State Up to a common ancestor so all the components that need to either access the current language strings, or to update the current language.

Using the Context API may actually be a better use case for you so you won’t need to explicitly pass all the strings data down to each component as props.

This is a similar approach many localization libraries use, i.e. they have a sting provider and expose a function to take a string id and the current set language return the correct localized text. React-intl is one such popular localization library.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement