How to declare a global variable in React?

前端 未结 9 1213
自闭症患者
自闭症患者 2020-11-29 23:21

I initialized i18n translation object once in a component ( first component that loads in the app ) . That same object is required In all other components. I do

相关标签:
9条回答
  • 2020-11-30 00:14

    Beyond React

    You might not be aware that an import is global already. If you export an object (singleton) it is then globally accessible as an import statement and it can also be modified globally.

    If you want to initialize something globally but ensure its only modified once, you can use this singleton approach that initially has modifiable properties but then you can use Object.freeze after its first use to ensure its immutable in your init scenario.

    const myInitObject = {}
    export default myInitObject
    

    then in your init method referencing it:

    import myInitObject from './myInitObject'
    myInitObject.someProp = 'i am about to get cold'
    Object.freeze(myInitObject)
    

    The myInitObject will still be global as it can be referenced anywhere as an import but will remain frozen and throw if anyone attempts to modify it.

    If using react-create-app

    (what I was looking for actually) In this scenario you can also initialize global objects cleanly when referencing environment variables.

    Creating a .env file at the root of your project with prefixed REACT_APP_ variables inside does quite nicely. You can reference within your JS and JSX process.env.REACT_APP_SOME_VAR as you need AND it's immutable by design.

    This avoids having to set window.myVar = %REACT_APP_MY_VAR% in HTML.

    See more useful details about this from Facebook directly:

    https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

    0 讨论(0)
  • 2020-11-30 00:20

    Here is a modern approach, using globalThis, we took for our React Native app.

    globalThis is now included in...

    • Modern browsers - MDN documentation
    • Typescript 3.4 - Handbook documentation
    • ESLint v7 - Release notes


    appGlobals.ts

    // define our parent property accessible via globalThis. Also apply the TypeScript type.
    var app: globalAppVariables;
    
    // define the child properties and their types. 
    type globalAppVariables = {
      messageLimit: number;
      // more can go here. 
    };
    
    // set the values.
    globalThis.app = {
      messageLimit: 10,
      // more can go here.
    };
    
    
    // Freeze so these can only be defined in this file.
    Object.freeze(globalThis.app);
    


    App.tsx (our main entry point file)

    import './appGlobals'
    
    // other code
    


    anyWhereElseInTheApp.tsx

    const chatGroupQuery = useQuery(GET_CHAT_GROUP_WITH_MESSAGES_BY_ID, {
      variables: {
        chatGroupId,
        currentUserId: me.id,
        messageLimit: globalThis.app.messageLimit, //                                                                     
    0 讨论(0)
  • 2020-11-30 00:21

    Create a file named "config.js" in ./src folder with this content:

    module.exports = global.config = {
        i18n: {
            welcome: {
                en: "Welcome",
                fa: "خوش آمدید"
            }
            // rest of your translation object
        }
        // other global config variables you wish
    };
    

    In your main file "index.js" put this line:

    import './config';
    

    Everywhere you need your object use this:

    global.config.i18n.welcome.en
    
    0 讨论(0)
提交回复
热议问题