Created
October 18, 2019 18:36
-
-
Save debabrata100/8b80aafa6166f42b78c3ebd43e14b5a7 to your computer and use it in GitHub Desktop.
On Change of locale save to react state and store locale value to localStorage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from 'react'; | |
import './App.css'; | |
const defaultLocale = localStorage['locale'] ? localStorage['locale'] : 'en'; // English is default locale if none is set | |
const localeList = [ | |
{ name: 'English', code: 'en', lang: 'English' }, | |
{ name: '中文', code: 'zh', lang: 'Chinese' }, | |
{ name: 'русский', code: 'ru', lang: 'Russian' }, | |
{ name: 'Française', code: 'fr', lang: 'French' } | |
]; | |
function App() { | |
const [currentLocale, setCurrentLocale] = useState(defaultLocale); | |
const onChangeLanguage = (e) => { | |
const selectedLocale = e.target.value; | |
setCurrentLocale(selectedLocale); | |
localStorage.setItem('locale',selectedLocale) | |
} | |
return ( | |
<div className="App"> | |
<h1>Localization in Create React App</h1> | |
<select onChange={onChangeLanguage} defaultValue={currentLocale}> | |
{ | |
localeList.map((locale,index)=>( | |
<option key={index} value={locale.code}>{locale.name}</option> | |
)) | |
} | |
</select> | |
<footer>Love you 3000 <span>♠</span></footer> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment