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

avatar

Borislav Hadzhiev

Mon May 02 20222 min read

banner

Photo by Maria Camargo

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

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.

The "X is not defined error" often occurs when we try to import a local file as 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.

App.js
// 👇️ 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.

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.