Borislav Hadzhiev
Mon May 02 2022·2 min read
Photo by Maria Camargo
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 above 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.
import './myFile'
instead of import myFunction from 'myFile'
.If you are getting the error when using local members (not from 3rd party packages), 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 above 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.