3

As title. I've searched about this problem on this site but I didn't find a solution for my case. I've defined a global variables in public/static/js/A.js in my Visual Studio project:

var pVariable=new Class1();

There is a function LoadList() in Class1.
That variable will be used in several functions in my project, so I set as a global variable, and I included the JS file to public/index.html in the same project:

<script type="text/javascript" src="%PUBLIC_URL%/static/js/A.js"></script>

I use that variable in src/Clsb.js in the same project....

var alist=pVariable.LoadList();
export default class Clsb extends Component{
    render(){
        return (<Table dataSource={alist} />);
    }
}

When I start debug in Visual Studio , I got an error:Failed to compile: 'pVariable' is not defined no-undef
But I am sure the JS file contains that variable is included. Could someone guide me to fix where I made it wrong?

2
  • 1
    no-undef is an ESLint rule - you need to define the globals in your ESLint configuration, so it knows they'll be available. See eslint.org/docs/user-guide/configuring. Commented Jan 7, 2021 at 10:12
  • Global variables are generally a bad idea. I don't know React but perhaps values that need to available throughout your code should be available via a service. Commented Jan 7, 2021 at 10:13

3 Answers 3

5

You can do that by storing the variable in window variable

first store the value of your variable in A.js like this

window.pie = 3.1416;

And you can see the variable value in your Clsb.js component like

console.log(window.pie);
Sign up to request clarification or add additional context in comments.

Comments

3

As phuzi said in the comment to your question, declaring global variables in react is a bad idea, in this case the ideal would be to use redux, or else the context api (context hook) so you can access and make the variable available throughout your system.

Link to docs https://reactjs.org/docs/context.html

👇 context with functional component

let's create a context like hook

/src/context.js

import React, { createContext, useState, useContext} from "react";

const UserContext = createContext();

export default function UserProvider({ children }) {

//your variables
//example
const [person, setPerson] = useState('John');


    return (
        <UserContext.Provider
            value={{
                person //variables to export
            }}
        >
            {children}
        </UserContext.Provider>
    );
}

export function useUser() {
    const context = useContext(UserContext);
    
    if (!context) throw new Error("useUser must be used within a CountProvider");

    const { person } = context;

    return { person };
}

after creating the context, around your app you need to place the provider

index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

import UserProvider from "./src/context.js";

ReactDOM.render(
    <UserProvider>
        <React.StrictMode>
            <App />
        </React.StrictMode>
    </UserProvider>,
    document.getElementById("root")
);

after you already have the provider you can access any file

src/page.js

import React from "react";
import { useUser } from "./context.js";


const Page = (props) => {

const { getPerson } = useUser(); //variable available by context

return (<h1>Test h1</h1>)
};

export default Page ;

obs: i didn't test the code

Comments

0

Global variables is not a good practice in React. Whenever you find you find yourself needing that, it's most likely that what you want us instead Global state Management. My recommendation is : -first to try React's built in global state Management toolsn like Context API https://reactjs.org/docs/context.html -Then if the first doesn't serve your need, try third party state Management libraries like redux from https://react-redux.js.org/introduction/ or mobx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.