Search code examples
javascriptreactjsweb-applicationsreact-routerreact-router-redux

React JS Error "...rest" Syntax error: Unexpected token


I am new to React and looking at this ReactTraining. I would like to make some of my paths private (that way you can only view them when you are logged in). I am able to authenticate users fine and direct them to a new page, but now I would like to "Protect" that page so that it is only accessible after logging in. I found a few different sources that seem to use the same "PrivateRoute" function below. Everything seems to work great so far (and makes sense), except for the "...rest" part of this following code:

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    fakeAuth.isAuthenticated ? (
      <Component {...props}/>
    ) : (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    )
  )}/>
)

I am getting the following error:

Uncaught Error: Cannot find module "./components/Login"
    at webpackMissingModule (router.js:9)
    at Object.<anonymous> (router.js:9)
    at __webpack_require__ (bootstrap 18b9132…:555)
    at fn (bootstrap 18b9132…:86)
    at Object.<anonymous> (index.js:22)
    at __webpack_require__ (bootstrap 18b9132…:555)
    at fn (bootstrap 18b9132…:86)
    at Object.<anonymous> (bootstrap 18b9132…:578)
    at __webpack_require__ (bootstrap 18b9132…:555)
    at bootstrap 18b9132…:578
webpackMissingModule @ router.js:9
(anonymous) @ router.js:9
__webpack_require__ @ bootstrap 18b9132…:555
fn @ bootstrap 18b9132…:86
(anonymous) @ index.js:22
__webpack_require__ @ bootstrap 18b9132…:555
fn @ bootstrap 18b9132…:86
(anonymous) @ bootstrap 18b9132…:578
__webpack_require__ @ bootstrap 18b9132…:555
(anonymous) @ bootstrap 18b9132…:578
(anonymous) @ bootstrap 18b9132…:578
webpackHotDevClient.js:233 Error in ./src/components/Login.js
Syntax error: Unexpected token (16:46)

  14 | 
  15 | 
> 16 | const PrivateRoute = ({ component: Component, ...rest }) => (
     |                                               ^
  17 | <Route {...rest} render={props => (
  18 |   fakeAuth.isAuthenticated ? (
  19 |     <Component {...props}/>

 @ ./src/router.js 25:13-42

It appears that I am importing everything that I should be so my thought is that I don't have something installed that should be.

Does anyone know what I may need to install to resolve this error?


Solution

  • The spread ... syntax is not part of the es2015 or react babel presets. It's currently a stage 3 proposal. To enable support for spread in your React project, install the babel stage 3 plugin:

    npm install --save-dev babel-preset-stage-3
    

    and add it to your .babelrc:

    {
      "presets": [
        "es2015",
        "react",
        "stage-3"
      ]
    }