Search code examples
reactjsreact-i18next

how to translate string in a component using react-i18next?


i have a dropdown menu that lists say option1, option2 and option3. i would like to translate these options using react-i18next. I am new to translations and using this framework.

Below is the code,

export default class Example extends React.Component {
    render() {
        return (
            <ParentComponent>
                <button type="button">
                    {this.props.placeholder}
                </button>
                {this.props.values.map(value => (
                    <Item
                        key={value[this.props.value_prop]}
                        value={value}
                        on_select={this.change}>
                        {value[this.props.label_prop]} // i want to 
                        translate this
                    </Item>
                ))}
            </ParentComponent>
        );
}

Could someone provide an idea of how to go about this...or help me solve this. thanks.


Solution

  • react-i18next contains pretty good documentation and they also offer some examples.

    You basically need to wrap your componenent in a withTranslation wrapper and use the t props:

    import { useTranslation, withTranslation, Trans } from 'react-i18next';
    import logo from './logo.svg';
    import './App.css';
    
    // use hoc for class based components
    class LegacyWelcomeClass extends Component {
      render() {
        const { t, i18n } = this.props;
        return <h2>{t('title')}</h2>;
      }
    }
    const Welcome = withTranslation()(LegacyWelcomeClass);
    

    You haven't posted your full component code, but here's how it should look like:

    class CompClass extends Component {
        render() {
            const { t, i18n } = this.props;
            return (
                <ParentComponent>
                    <button type="button">
                        {this.props.placeholder}
                    </button>
                    {this.props.values.map(value => (
                        <Item
                            key={value[this.props.value_prop]}
                            value={value}
                            on_select={this.change}>
                            {t(value[this.props.label_prop])} // i want to translate this
                        </Item>
                    ))}
                </ParentComponent>
            );
        }
    }
    
    const Comp = withTranslation()(CompClass);