0

I have a file variables.js in top src directory, it declares a global variable.

declare var the_top;

In a component I want to access this variable but it claims it's not declared?

import React, {useEffect, useState} from "react";
import {the_top} from "../variables";

const TopElement = (props) => {
    const [topElement, setTopElement] = useState();

    the_top = "test";

Gives

ReferenceError: assignment to undeclared variable the_top
0

2 Answers 2

3

In variables.js use export var the_top instead. Then import it using import { the_top } from './variables' Keep in mind that importing a variable makes it read only and therefore, you won't be able to execute the_top = 'blabla'

If you want to make your variable properly global, assign it to window instead : window.the_top = 'test' and then print it using console.log(window.the_top)

Also, declare is not a thing is JS. Only in typescript to declare a type

Sign up to request clarification or add additional context in comments.

2 Comments

I don't understand this. When I write export var the_top = "bla"; and in the useEffect console.log(the_top); it prints "bla" to the console but when I put the_top = "blabla" I before that console.log, get the reference error again.
And when I write window.the_top = "blabla" I don't get a reference error but console.log still prints only "bla"
1

using export default the_top , there isn't a need to destructure .
Simply type import the_top from '../variables' (Only 1 default variable can be exported)
as mentioned above use window.the_top for global variable. Anyways, all the variables need to be exported that are to be used in another file.

1 Comment

It works with default export, but I need to export more variables in that file. Can't default export multiples

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.