Search code examples
javascriptnode.jsreactjscreate-react-app

Reactjs not understanding ES6?


I'm reeeally new to reactjs and I was copying a tutorial (link: https://www.youtube.com/watch?v=Ke90Tje7VS0). I'm currently on Windows and did the following on cmd (as per tutorial):

npm i -g [email protected]
create-react-app

The files/directories, etc. have all been installed, but I noticed that my App.js features this syntax:

function App()
{
    return(...);
}

While the App.js from the tutorial (and many other demos) use this kind of syntax, from what I understand it's ES6:

class App extends Component
{
    render() 
    {
        return(...);
    }
}

I tried copying this syntax onto my App.js but then my react app (from typing npm start in cmd) broke. How can I fix this (i.e. use the ES6 code without breaking my project)? Does it have the exact same functionality as my above code anyway?

Here is my error message:

  Line 8:  Parsing error: Unexpected token

   6 | class App extends Component {
   7 |   return (
>  8 |     <div className="App">
     |     ^
   9 |       <header className="App-header">
  10 |         <img src={logo} className="App-logo" alt="logo" />
  11 |         <p>

I really doubt it's a parsing error, the JSX worked fine with function App(), but when I changed it to class App extends Component without touching anything else, the program broke.


Solution

  • The issue here is from trying to return HTML/JSX from your class directly, rather than from within a function. If you're using a class, you'll need to wrap the returned HTML/JSX in the render function.

    For example:

    class App extends Component {
        render() {
            return (...)
        }
    }
    

    Also, regarding the difference between the two syntax examples you posted: the first is what's called a functional component, while the second is a class-based component. In the past, class-based components were used for anything that required state (data held and manipulated internally) or life-cycle methods, while functional components were used for components that were presentation-only. With Hooks (introduced , functional components can now have state and access to life-cycle methods so the two are pretty much equivalent. Put simply, you can think of a functional-component as just the render method of a class-based component.

    In general the difference in use goes like this:

    Class-based:

    class App extends Component {
        render() {
            return (...)
        }
    }
    

    Functional:

    const App = props => { // or function App(props) {
        return (...)
    }
    

    Check out these docs for a bit more detail: