'X' is not defined react/jsx-no-undef Error in React

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
2 min

banner

# 'X' is not defined react/jsx-no-undef Error in React

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'.

App.js
// ๐Ÿ‘‰๏ธ 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;

react not defined no undef

The code for this article is available on GitHub

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.

App.js
import {useState} from 'react';
Look at your error message and make sure to import the function that is causing the error before using it.

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.

App.js
// ๐Ÿ‘‡๏ธ 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.

# Importing local files

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.

App.js
// ๐Ÿ‘‡๏ธ 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.

another-file.js
// ๐Ÿ‘‡๏ธ named export export const myFunc1 = () => { console.log('hello world'); } // ๐Ÿ‘‡๏ธ default export export default function myFunc2() { console.log('hello world'); }
The code for this article is available on GitHub

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev