Import object in React not defined

Viewed 389

In React:

wording.js

export  const wording = {
  id1: 'record',
  id2: 'play'
};

test.js

import { wording } from "...";

function Test(props) {

  const onCellClicked = (e) => {
    console.log("Hello", wording.id1);
    if(wording.id1 ) {
      ...
    }
  }

  return (
    <button onClick={onCellClicked} >Press me</button>
  )

}

When I am calling and pressing the button, console.log responds correctly (getting record). However, by using Chrome Dev Tools and putting a break-point on if, wording is not defined!! Any logical explanation on that?

enter image description here

2 Answers

... putting a break-point on if, wording is not defined ...

Wich wording ? In your file, you have 2 places where you use wording.

In the react file, there is 2 places with the certain variable

  • The place where you import it
  • The place where you reference it (use it)

If you hover on the place where you use it, you will see the variable value

e.g.

enter image description here

But if you hover where you import it, it will be undefined

enter image description here

That happens because the variable of the import is out of scope and you certain won't be able to see it's value.

This happened to me. Sometimes React compiled it, sometimes it didn't. This seems to be proper syntax so I can't tell you why this happens but I can tell you what I did to fix it. I just had to restructure my files a little bit. So for yours, you would change:

wording.js

export default {
  id1: 'record',
  id2: 'play'
};

test.js

import wording from "...";

function Test(props) {

  const onCellClicked = (e) => {
    console.log("Hello", wording.id1);
    if(wording.id1 ) {
      ...
Related