Bdouce
Bdouce

Reputation: 23

Babel does not transpile a JSX instance of an arrow function

my Javascript & React level is beginner.

I'm having fun with https://babeljs.io/repl to see how my JSX is transpiled into an older version of Javascript, and there is something I don't quite understand.

I'm trying to use an arrow function and an instance of this function :

const App = () => {
    return <div></div>;
}

<App></App>

Which throws me an error :

repl: Unexpected token (5:6)
  3 | }
  4 | 
> 5 | <App></App>
    |       ^

Note that a normal function AND it's instance () is working fine. An arrow function ONLY is working fine too. The problem happens when i use an arrow function AND the JSX instanciation of it.

Thank you !!

Upvotes: 1

Views: 85

Answers (2)

catchergeese
catchergeese

Reputation: 732

Please also note that having <App></App> on file-level scope - while being technically correct - will result in discarding a value that it produces - no component will be mounted. Usually, one would use ReactDOM's render method to render React components' tree:

const root = document.getElementById("root");
ReactDOM.render(<App />, root)

Upvotes: 1

Estus Flask
Estus Flask

Reputation: 222369

The problem happens when i use an arrow function AND the JSX instanciation of it.

That's the problem here. In order to be parsed correctly, <App></App> should be unambiguously identified as JSX. This cannot be done because a semicolon after an arrow was omitted.

It should be:

const App = () => {
    return <div></div>;
};

<App></App>

As another answer mentions, JSX syntax is usually used in situations like ReactDOM.render(...) where it can be unambiguously identified as an expression, so this problem won't occur in this case.

Upvotes: 1

Related Questions