You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何使用React.Fragment会触发React.createElement无效类型控制台错误?

Fixing the "React.createElement: type is invalid" Warning with React.Fragment

Hey, I’ve hit this exact snag before—total head-scratcher when swapping a <div> for <React.Fragment> suddenly breaks everything! Let’s walk through the most likely culprits and how to fix them:

1. You forgot to import React entirely

JSX relies on React.createElement under the hood, and <React.Fragment> is a property of the React object. If your component file doesn’t import React, React will be undefined—so React.Fragment is also undefined, triggering that warning.

Wrong:

// Missing import!
function MyComponent() {
  return (
    <React.Fragment>
      <p>Hello</p>
      <p>World</p>
    </React.Fragment>
  );
}

Right:

import React from 'react'; // This is mandatory!

function MyComponent() {
  return (
    <React.Fragment>
      <p>Hello</p>
      <p>World</p>
    </React.Fragment>
  );
}

Pro tip: You can also use the shorter <> syntax for fragments (no need to write React.Fragment), but you still need to import React for JSX to work.

2. You messed up named vs default imports (if using standalone Fragment)

If you’re trying to import Fragment directly instead of using React.Fragment, make sure you use named imports—Fragment is not a default export from React.

Wrong:

import Fragment from 'react'; // ❌ Fragment is a named export, not default

function MyComponent() {
  return (
    <Fragment>
      <p>Oops</p>
    </Fragment>
  );
}

Right:

import React, { Fragment } from 'react'; // ✅ Named import

function MyComponent() {
  return (
    <Fragment>
      <p>Fixed!</p>
    </Fragment>
  );
}

Or stick with import React from 'react' and use <React.Fragment>—either works, just don’t mix up the import style.

3. Your React version is too old

React.Fragment was introduced in React 16.2.0. If you’re using a version older than that, React.Fragment doesn’t exist at all—it’ll return undefined, causing the error.

To check your React version:
Run this in your project terminal:

npm list react
# Or if using Yarn:
yarn list react

If the version is below 16.2.0, upgrade it:

npm install react@^16.2.0 react-dom@^16.2.0 --save
# Yarn:
yarn add react@^16.2.0 react-dom@^16.2.0

4. Typos in the Fragment name

It sounds silly, but it happens! Double-check you’re writing <React.Fragment> with a capital F—lowercase <react.fragment> or misspellings like <React.Fragement> (missing an r) will all result in an undefined type.


Start with checking the React import first—it’s the most common fix. If that’s not it, verify your version or import syntax, and you’ll be back to using fragments instead of extra divs in no time!

内容的提问来源于stack exchange,提问作者AnApprentice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:55:35