69

I'm building a React app, with create-react-app.

I got the following error when running ESLint:
8:3 error 'document' is not defined no-undef.

My app runs without error, but I got this ESLint error in 2 files. See one of those .jsx files and my ESLint configuration.

index.jsx:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
  <App />,
  document.getElementById('root'),
);

eslintrc.js:

module.exports = {
  "extends": "airbnb",
  "plugins": [
      "react",
      "jsx-a11y",
      "import"
  ],
  "env": {
    "jest": true
  }
};

How can I fix this ? For the moment I will simply ignore both files ... but I'd rather find a long term solution.

Thomas Sauvajon
  • 1,660
  • 2
  • 13
  • 26

4 Answers4

119

Add "browser": true your env to include global variables (like document, window, etc.)

See the ESLint environment documentation for more information.

Lucas
  • 4,067
  • 1
  • 20
  • 30
46

set an env property in you eslint.rc file, e.g.

{
    "env": {
        "browser": true,
        "node": true
    }
}
Hom Bahrani
  • 3,022
  • 27
  • 25
  • 2
    Although @Locus answer is ok, but this is a better solution as it's not dependent to a link (which might got broken on day) and it describes the steps to solve the probelm – Ghasem Feb 01 '20 at 10:49
8

If you have .eslintrc.json file then add following code snippet.

{
    ...otherSettings,
    "env": {
        "browser": true,
        "node": true
    }
}

if you do not have .eslintrc.json then you can add these settings in you package.json file.

{
    ...otherSettings,
    "eslintConfig": {
      "globals": {
        "window": true
      }
    }
}
Ajay Rawat
  • 307
  • 3
  • 10
7

In your package.json, specify the test environment for jest as "jsdom" as follows:

  "jest": {
    "testEnvironment": "jsdom"
  }

I faced the same issue and it worked well for me.

Peter
  • 10,492
  • 21
  • 82
  • 132
  • 1
    No clue why this isn't the top result on google. It's definitely the solution. I didn't realize what the facebook react test script was doing with its -env=jsdom command line argument – Steve Nov 07 '17 at 04:20