You are building a Next.js app and encounter the following error:
Error: Unexpected token `div`. Expected jsx identifier
As an example, adding the following code to the /src/app/page.tsx
file will cause the error:
export default function Home() { const casesArr = [{ id: 1, name: "Case 1" }, { id: 2, name: "Case 2" }, { id: 3, name: "Case 3" }]; return ( <div> <ul> {casesArr.map((case) => ( <li key={case.id}>{case.name}</li> ))} </ul> </div> ); }
The Unexpected token error is a JavaScript syntax error. It occurs when a specific language construct is expected but not provided. In this case, TypeScript was expecting JSX to be returned but came across something unexpected.
The issue may be due to a typo. It can also be due to using reserved JavaScript words, missing property values, extra or missing parentheses, or due to a trailing comma being in a place where an expression is expected.
To fix the code example above, change the name of the callback function argument in the map
array method:
export default function Home() { const casesArr = [{ id: 1, name: "Case 1" }, { id: 2, name: "Case 2" }, { id: 3, name: "Case 3" }]; return ( <div> <ul> {casesArr.map((caseItem) => ( <li key={caseItem.id}>{caseItem.name}</li> ))} </ul> </div> ); }
The word case
is a reserved word in JavaScript. You can’t use reserved words as identifiers for variables, functions, classes, etc.
The error can also be caused by a missing property value:
<Image src="/next.svg" alt="logo" width={} height={200} />
An extra parenthesis can cause the issue:
<Image src="/next.svg" alt="logo" width={20} height={200}} />
Missing parentheses can also cause an error:
<Image src="/next.svg" alt="logo" width={20} height={200 />
If you add a trailing comma where an expression is expected, such as after a map()
function, you’ll get the error:
<ul> {casesArr.map((caseItem) => ( <li key={caseItem.id}>{caseItem.name}</li> )),} </ul>
You can fix the error by removing the comma, or by adding an expression like:
<ul> {casesArr.map((caseItem) => ( <li key={caseItem.id}>{caseItem.name}</li> )).reverse()} </ul>
Get actionable, code-level insights to resolve Next.js performance bottlenecks and errors.
Run the line of code below to:
Create a free Sentry account
Run the CLI install command to automatically add the Sentry SDK to your project:
npx @sentry/wizard@latest -i nextjs
Start capturing errors and performance issues
Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.