Last updated: Apr 7, 2024
Reading timeยท2 min
The React.js error "X is not defined react/jsx-no-undef" occurs when we forget to import a function, class or a variable in our code before using it.
To solve the error, make sure to import the value before using it in your
code, e.g. import {myFunc} from 'my-package'
.
// ๐๏ธ Forgot to import `useState` const App = () => { // โ๏ธ 'useState' is not defined no-undef // Uncaught ReferenceError: useState is not defined const [count, setCount] = useState(0); const handleClick = event => { setCount(current => current + 1); }; return ( <div> <h2>Count: {count}</h2> <button onClick={handleClick}>Increment</button> </div> ); }; export default App;
The issue in the example is that we have forgotten to import the useState
hook
before using it.
To solve the error, we have to import the function.
import {useState} from 'react';
Your error message should contain the name of the function you have to import.
There are 2 types of imports in ES6 - named
and default
imports.
// ๐๏ธ named import import {myFunc1} from 'my-package'; // ๐๏ธ default import import myFunc2 from 'my-package';
Which type of import you have to use to import the function depends on how it was exported.
The error often occurs when we try to import a local file as import './myFile'
instead of import myFunction from 'myFile'
.
If you got the error when using local members (not from a third-party package), make sure to specify a relative path in your import statement.
// ๐๏ธ named import import {myFunc1} from './another-file'; // ๐๏ธ default import import myFunc2 from './another-file';
The example assumes that you have a file called another-file.js
located in the
same directory as App.js
.
Make sure to export the function you're trying to use from another-file.js
.
// ๐๏ธ named export export const myFunc1 = () => { console.log('hello world'); } // ๐๏ธ default export export default function myFunc2() { console.log('hello world'); }
For example, if you need to import from one directory up, you would import as
import {myFunc1} from '../another-file'
.
Once you import all of the functions you are using, the error will be resolved.
If you get the error Unexpected use of 'X' no-restricted-globals, click on the link and follow the instructions.