Codesandbox提示React is not defined,本地VSCode运行正常
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.jsondependencies to confirm). - Check tsconfig.json: Make sure your
jsxsetting is"jsx": "react-jsx"(for the automatic JSX transform) instead of the older"react"option. - Confirm dependencies: Double-check that
reactand@types/reactare installed in your Codesandbox project (most templates include these, but it’s worth verifying).
内容的提问来源于stack exchange,提问作者me.at.coding

