Search code examples
javascriptreactjsreact-bootstrapreact-i18next

Show chosen i18next language in react-bootstrap select input


import React from 'react';
import i18n from "i18next";
import { withTranslation, WithTranslation } from 'react-i18next';
import {Form} from 'react-bootstrap';

interface State {
    language: string;
}

interface Props extends WithTranslation {}

class LanguageSwitcher extends React.Component<WithTranslation, State, Props> {

    constructor(props: Props) {
        super(props);
        this.state = {
            language: 'en'
        };
    }

    changeLang = async (event: any) => {
        i18n.changeLanguage(event.target.value);
        this.setState({...this.state, language: event.target.value});
        await new Promise(r => setTimeout(r, 200));
    }

    render() {
        const { t, i18n } = this.props;
        const getCurrentLng = () => i18n.language || window.localStorage.i18nextLng || '';

        return (
            <div className="tmf-language-switcher">
                <Form>
                    <Form.Group controlId="form-language">
                        <Form.Label>{t('language')}</Form.Label>
                        <Form.Control value={this.state.value} as="select" onChange={this.changeLang.bind(this)} ref="valid_for">
                            <option value="en">{t('English')}</option>
                            <option value="de">{t('German')}</option>
                        </Form.Control>
                    </Form.Group>
                </Form>
            </div>
        );
    }
}

export default withTranslation()(LanguageSwitcher);

I am using react-i18next and react-bootstrap to implement a language switcher.

The code above works and I can switch the languages, but if I change the route and come back, the current language is not selected in the control options.

Can somebody tell me, how to show the correct as default regarding the language?


Solution

  • I solved it by passing getCurrentLng() as value to my Form.Control:

    <Form.Control value={getCurrentLng()} as="select" onChange={this.changeLang.bind(this)}>