Home > Software design >  How to resolve Unexpected Token Error in nextJS project?
How to resolve Unexpected Token Error in nextJS project?

Time:08-29

I set up a new "next.js" project and wanted to start coding, but I'm now stuck for hours with the below error message.

I've taken a reference code to start with as below -

import styled from "styled-components";

function Sidebar() {
    return {

        <Container> 
            <h1> Sidebar </h1>
        </Container>

    }
}

export default sidebar;

const Container = styled.div;

This is the error:

      x Unexpected token `< (jsx tag start)`. Expected identifier, string literal, numeric literal or [ for the computed key   
   ,----
 7 | <Container>
   : ^
   `----

Of course, I did my Google research and tinkered around in different config files. There are a lot of different solutions, but none worked for me (so far). My guess is that it's something to do with the babel configuration., but I am groping in the dark.

My .babelrc file:

{
  "presets": ["env"],
  "plugins": [
    ["transform-replace-object-assign", { "moduleSpecifier": "object.assign" }],
    "transform-object-rest-spread",
    // "@babel/plugin-proposal-nullish-coalescing-operator", // TODO: update to babel 7
  ],
}

Look to see the guidance on this.

CodePudding user response:

You must use () braces with the return statement.

return (
  <Container>
    <h1> Sidebar </h1>
  </Container>
);

CodePudding user response:

When returning a JSX expression, you have to use parentheses to contain the JSX, not curly braces.

function Sidebar() {
  return (
    <Container> 
      <h1> Sidebar </h1>
    </Container>
  );
}

Some more reading on why parentheses in the return expression is important: https://hashnode.com/post/why-some-returns-in-react-use-round-brackets-while-some-use-curly-brackets-cjgjul2r7002xwcs222e4hp2s

  • Related