I want to duplicate Material UI's language changer https://material-ui.com/.
So as you can see, I wrapped an icon + Mui Select into a Mui Button. By the way, if you have an idea for a better implementation you're welcome!
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { Select, MenuItem, Button } from '@material-ui/core';
import { useTranslation } from 'react-i18next';
import TranslateIcon from '@material-ui/icons/Translate';
const useStyles = makeStyles(() => ({
root: {
'&:before': {
borderColor: 'white',
},
'&:after': {
borderColor: 'white',
},
color: 'white',
},
}));
const LanguageChanger = () => {
const classes = useStyles();
const { i18n, t } = useTranslation();
const listLanguage = React.createRef();
const langSwitch = [
{ code: 'en-US', title: t('Language.English') },
{ code: 'fr', title: t('Language.French') },
];
const handleChange = event => {
i18n.changeLanguage(event.target.value);
};
const renderSelect = language => {
return (
<Button
color='inherit'
onClick={() => {
console.log(listLanguage);
listLanguage.current.click();
}}
>
<TranslateIcon />
<Select
className={classes.root}
id='select-language'
ref={listLanguage}
value={language}
onChange={handleChange}
>
{langSwitch.map((lang, index) => {
return (
<MenuItem key={index} value={lang.code}>
{lang.title}
</MenuItem>
);
})}
</Select>
</Button>
);
};
return renderSelect(i18n.language);
};
export default LanguageChanger;
My problem here is to open MuiSelect with a click on his parent's Mui Button. No errors, the Mui Select is just taking the focus.