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

Codesandbox提示React is not defined,本地VSCode运行正常

Fixing "React is not defined" Error in Codesandbox for Your TSX Component

This error crops up due to a mismatch in how your local development environment and Codesandbox handle JSX compilation. Here's a quick fix, plus context on why it's happening and extra troubleshooting steps:

Quick Solution

Add an explicit import for React at the top of your MyTable.tsx file—even though you're already importing hooks and types:

import React, { FC, useState } from "react";

interface Row {
  id: number;
  content: string;
}
interface Props {
  initialRows: Row[];
}
export const MyTable: FC<Props> = function ({ initialRows }) {
  const [rows, setRows] = useState(initialRows);
  return (
    <table>
      <tbody>
        {rows.map((row, index) => (
          <tr key={`id${row.id}`}>
            <td>{row.content}</td>
            <td>
              <button type="button" onClick={() => {
                const newRows = [...rows];
                newRows.splice(index, 1);
                setRows(newRows);
              }}
              >
                remove
              </button>
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
};

Why This Works (And Why It Worked Locally)

Local tools like Create React App v5+ or Vite enable the React 17+ JSX Transform by default. This feature lets you use JSX without explicitly importing React because the compiler automatically injects the necessary code behind the scenes.

However, some Codesandbox templates (especially older ones) might not have this transform enabled, or could be using a React version older than 17. In those cases, JSX gets compiled to React.createElement() calls, which requires the React variable to be in scope—hence the "not defined" error.

Extra Troubleshooting Steps

If adding the import doesn’t resolve the issue, check these details:

  • Verify React version: Ensure Codesandbox is using the same React version as your local project (check package.json dependencies to confirm).
  • Check tsconfig.json: Make sure your jsx setting is "jsx": "react-jsx" (for the automatic JSX transform) instead of the older "react" option.
  • Confirm dependencies: Double-check that react and @types/react are installed in your Codesandbox project (most templates include these, but it’s worth verifying).

内容的提问来源于stack exchange,提问作者me.at.coding

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:48:14