I implemented a switch button on a single webpage to enable the user to select between two languages (english and french) - I am trying to use React and i18next library. So far the switch button does the job but I would like to save the user preference in local storage and until now I did not succeed to complete that task.
As you will notice in the code below I did some tests, replacing the initial state of the switch button (checked: false
) by : checked: (lngSelect ? lngSelect : false)
But this doesn't work unfortunately. Also I have no idea if my code is clean enough, I mean if this is the usual way to do that kind of thing.
import React, { useState } from 'react';
import Switch from '@material-ui/core/Switch';
import { useTranslation } from 'react-i18next';
import footerStyles from '../../styles/footer.module.scss';
function SwitchBtn() {
const lngSelect = localStorage.getItem('LngSelect');
const { i18n } = useTranslation();
const [state, setState] = useState({
checked: (lngSelect ? lngSelect : false)
// checked: false
});
function handleTranslation(state) {
if (state) {
i18n.changeLanguage('fr');
} else {
i18n.changeLanguage('en');
}
localStorage.setItem('LngSelect', JSON.stringify(state));
}
return (
<Switch
className={footerStyles.switchBtn}
checked={state.checked}
onChange={(e) => {
setState({ checked: e.target.checked });
handleTranslation(e.target.checked);
}}
name="languagesSwitch"
/>
)
}
export default SwitchBtn