2
votes

I am trying to add the i18next translation system to my React app and I've already configured everything, but I can't seem to find how to change the language (using a select or a button, for example).

I've followed this easy guide to set the whole thing up. But there's nothing on how to manually change the language. And, as you can see here, there's a function to change the language, but it's inside a function component:

function Page() {
const { t, i18n } = useTranslation();

  const changeLanguage = lng => {
    i18n.changeLanguage(lng);
  };

  return ([...])
}

However, my component is a class extending from component and it doesn't seem to work the same way:

class Profile extends Component {
  [...]
}
export default withTranslation()(Profile);

How should I do it then? I've no clue.

2

2 Answers

4
votes

It throws some errors that I have not solved yet, but at least it works. Apparently, when in a function component (such as the one listed before), when using useTranslation, your t and i18n variables are obtained by calling useTranslation(). However, when using a class, t and i18n are obtained from this.props.

So, now the class looks like this:

import React, { Component } from "react";
import { withTranslation } from 'react-i18next';

class Profile extends Component {

  render() {
    const { t, i18n } = this.props;
    const changeLanguage = lng => {          
      i18n.changeLanguage(lng);
    };

    return (
      [...]
      <button onClick={() => changeLanguage('en')}>EN</button>
      [...]
    )
  }

  export default withTranslation()(UserProfile);

I'll edit the answer when I solve the warnings, but I'll leve this solution here in case someone has the same issue.

The error that I get is the following:

Uncaught Error: MobX Provider: The set of provided stores has changed. See: https://github.com/mobxjs/mobx-react#the-set-of-provided-stores-has-changed-error.

0
votes
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import { useTranslation } from "next-i18next";

// Use getServerSideProps or getStaticProps as convenience
export async function getServerSideProps({ locale }) {

  return {
    props: {
       ...(await serverSideTranslations(locale, ["common"]))
      },
  };

}

function YourComponent(props) {
   const { t, i18n } = useTranslation("common");
   console.log(i18n.language);
   return (<div>{i18n.language}</div>);
}

export default YourComponent;