React-Intl how to switch locale and messages from variable

后端 未结 3 519
Happy的楠姐
Happy的楠姐 2021-02-04 06:28

I\'m trying to figure out how to change language using React-Intl. This is my first React App and it has been made with create-react-app, I\'m not using Redux nor Flux.

3条回答
  •  死守一世寂寞
    2021-02-04 07:21

    With a new React Context API it is quite easy to do. Create a wrapper:

    import React from "react";
    import Types from "prop-types";
    import { IntlProvider, addLocaleData } from "react-intl";
    import en from "react-intl/locale-data/en";
    import de from "react-intl/locale-data/de";
    import deTranslation from "../../lang/de";
    import enTranslation from "../../lang/en";
    
    addLocaleData([...en, ...de]);
    
    const Context = React.createContext();
    
    class IntlProviderWrapper extends React.Component {
      constructor(...args) {
        super(...args);
    
        this.switchToEnglish = () =>
          this.setState({ locale: "en", messages: enTranslation });
    
        this.switchToDeutsch = () =>
          this.setState({ locale: "de", messages: deTranslation });
    
        // pass everything in state to avoid creating object inside render method (like explained in the documentation)
        this.state = {
          locale: "en",
          messages: enTranslation,
          switchToEnglish: this.switchToEnglish, 
          switchToDeutsch: this.switchToDeutsch 
        };
      }
    
      render() {
        const { children } = this.props;
        const { locale, messages } = this.state;
        return (
          
            
              {children}
            
          
        );
      }
    }
    
    export { IntlProviderWrapper, Context as IntlContext };
    

    And then use that Provider and Consumer:

    import { Provider } from "react-redux";
    import {  IntlProviderWrapper } from "./IntlContext";
    
    class App extends Component {
      render() {
        return (
          
            
              ...
            
          
        );
      }
    }
    

    somewhere in the app:

    import React from "react";
    import { Text, Button } from "native-base";
    import { IntlContext } from "../IntlContext";
    
    const LanguageSwitch = () => (
      
        {({ switchToEnglish, switchToDeutsch }) => (
          
            
            
          
        )}
      
    );
    
    // with hooks
    const LanguageSwitch2 = () => {
      const { switchToEnglish, switchToDeutsch } = React.useContext(IntlContext);
      return (
        <>
          
          
        
      );
    };
    
    export default LanguageSwitch;
    

    Example on CodeSandbox

    Here is the relevant repository with a more general solution.

    Note: at the moment react-intl is still using an old context API but in the future solution like this might work out-of-the-box.

提交回复
热议问题