Adding a LocaleSwitch component

Still needs some styling, but it is functional
This commit is contained in:
Jeff Avallone 2018-05-31 19:06:33 -04:00
parent 479d035cd0
commit efc8f6744a
5 changed files with 99 additions and 0 deletions

View File

@ -0,0 +1,14 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`LocaleSwitcher rendering 1`] = `
<label>
<Trans>
Language
</Trans>
<select
className="switcher"
onChange={[Function]}
value="en"
/>
</label>
`;

View File

@ -0,0 +1,65 @@
import React from 'react';
import { translate, Trans } from 'react-i18next';
import i18n from 'i18next';
import style from './style.css';
import locales from 'locales';
const localeToAvailable = (locale, available, defaultLocale) => {
if (available.includes(locale)) {
return locale;
}
const parts = locale.split('-');
if (parts.length > 0 && available.includes(parts[0])) {
return parts[0];
}
return defaultLocale;
};
class LocaleSwitcher extends React.PureComponent {
constructor() {
super();
this.state = {
current: localeToAvailable(i18n.language || '', Object.keys(locales), 'en')
};
}
localeSelector = React.createRef()
componentDidMount() {
i18n.on('languageChanged', this.handleLanguageChange);
}
componentWillUnmount() {
i18n.off('languageChanged', this.handleLanguageChange);
}
handleSelectChange = () => {
i18n.changeLanguage(this.localeSelector.current.value);
}
handleLanguageChange = lang => {
this.setState({ current: lang });
}
render() {
const { current } = this.state;
return <label>
<Trans>Language</Trans>
<select className={ style.switcher } value={ current } ref={ this.localeSelector } onChange={ this.handleSelectChange }>
{ Object.keys(locales).map(locale => (
<option value={ locale } key={ locale }>{ i18n.getFixedT(locale)('/displayName') }</option>
)) }
</select>
</label>;
}
}
export default translate()(LocaleSwitcher);
export { LocaleSwitcher };

View File

@ -0,0 +1,3 @@
.switcher {
margin-left: 1ex;
}

View File

@ -0,0 +1,16 @@
jest.mock('components/SVG');
import React from 'react';
import { shallow } from 'enzyme';
import { LocaleSwitcher } from 'components/LocaleSwitcher';
import { translate } from '__mocks__/i18n';
describe('LocaleSwitcher', () => {
test('rendering', () => {
const component = shallow(
<LocaleSwitcher t={ translate }/>
);
expect(component).toMatchSnapshot();
});
});

View File

@ -1,3 +1,4 @@
/displayName: English
404 Page Not Found: '404: Page Not Found'
Add It: Add It
Add Regexper to your home screen?: Add Regexper to your home screen?