DEV Community

Create a Multi-Language Website with React Context API

Halil Can Ozcelik on November 07, 2019

In this article, I will try to explain my approach to develop a multi-language website with React Context API. If you are used to reading code bett...
Collapse
 
sercanbozkurt profile image
Sercan

thank you bro :)

Collapse
 
giovabiancia profile image
Giovanni Bianciardi

Initial context doesn't change when calling userLanguageChange function.

export const LanguageBisContext = createContext({
userLanguage: "en",
dictionary: dictionaryList.en,
});

Collapse
 
halilcanozcelik profile image
Halil Can Ozcelik

I am not sure to understand your point but it is working as expected and here is the demo nice-cliff-047044a03.azurestaticap...

Collapse
 
wlaskovic profile image
wlaskovic

Thanks, that was super helpful!
Is it somehow possible to put flag icons instead of country name? I've tried with tag but I'm getting [object Object] instead of images

Collapse
 
halilcanozcelik profile image
Halil Can Ozcelik • Edited

Actually, your issue is about HTML most probably. I suppose you are trying to add img element in option tag of LanguageSelector.js You are most probably getting "Only strings and numbers are supported as option children" error in the console. So, if you want to use flags, you need to change the HTML structure of the LanguageSelector component.

Collapse
 
bernarda profile image
BernardA

Looks good! Will this work with SSR, specifically NextJS?
Thanks.

Collapse
 
halilcanozcelik profile image
Halil Can Ozcelik

Honestly, I didn't try in any SSR project but, I don't see any reason not to work.

Collapse
 
xurify profile image
Xuri

Really helpful post, tesekkur ederim! :)

Collapse
 
thanhluantl2304 profile image
thanhluantl2304

That looks good! But how would it be when i want to set the language for the Alert (which is not a component) ???

Collapse
 
ahmedkhalildeveloper profile image
AhmedKhalilDeveloper • Edited

Thank you very much, but there is a problem when using the tag on "placeholder"
It shows the following text: [object Object] Do you have a solution for this?

Collapse
 
halilcanozcelik profile image
Halil Can Ozcelik • Edited

Thank you for the beneficial question. You can use the language context directly. I added an example about it via this commit: github.com/hcoz/react-context-mult...
Also, I will update the article by adding this example.