Forgetting to import React when using JSX (React 17+ solves this)

Loading

The Classic Problem (Pre-React 17)

Before React 17, you needed to import React in every file using JSX because JSX was transformed into React.createElement() calls:

// Required pre-React 17
import React from 'react';

function MyComponent() {
  return <div>Hello World</div>;
}

Without this import, you’d get the error: ‘React’ must be in scope when using JSX.

The Modern Solution (React 17+)

React 17 introduced a new JSX transform that automatically imports the necessary functions, eliminating the need for explicit React imports:

// No React import needed in React 17+
function MyComponent() {
  return <div>Hello World</div>;
}

How to Set Up the New JSX Transform

1. For Create React App (v4+)

Already configured by default – no setup needed.

2. For Custom Webpack Configs

Update your Babel config:

npm install @babel/preset-react@^7.12.0
// babel.config.json
{
  "presets": [
    ["@babel/preset-react", {
      "runtime": "automatic"
    }]
  ]
}

3. For TypeScript (v4.1+)

Update tsconfig.json:

{
  "compilerOptions": {
    "jsx": "react-jsx"
  }
}

When You Still Need React Imports

Even with React 17+, you’ll need to import React when:

  1. Using React APIs directly:
   import { useState, useEffect } from 'react';
  1. Using React Context
  2. Working with older codebases

Migration Tips

  1. Check your React version:
   npm list react
  1. Update ESLint rules if needed:
   "rules": {
     "react/react-in-jsx-scope": "off"
   }
  1. Run a codemod to remove unused imports:
   npx react-codemod update-react-imports

Common Errors and Fixes

  1. “React is not defined”:
  • Update to React 17+ and configure the new transform
  • Or add the React import if staying on older versions
  1. Build tool errors:
   npm update @babel/core @babel/preset-react
  1. TypeScript errors:
   npm update typescript @types/react @types/react-dom

The new JSX transform is now the standard for all modern React development, resulting in cleaner component files and slightly smaller bundle sizes.

Leave a Reply

Your email address will not be published. Required fields are marked *