Shubham Goyal Shubham Goyal - 5 months ago 30
React JSX Question

Why is this exception being thrown? Uncaught ReferenceError: React is not defined

import {Route, IndexRoute} from 'react-router'
import App from './App'
import Home from './Home'
import Repos from './Repos'
import Repo from './Repo'
import About from './About'

module.exports = (
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="/repos" component={Repos}>
<Route path="/repos/:userName/:repoName" component={Repo} />
<Route path="/about" component={About}/>

I didn't expect to have to import React here. Of course, the fix is easy. I just need to add the following:

import React from 'react'

What is puzzling to me is that React is not explicitly used in the code sample I pasted above. I guess it is being required when the Babel/JSX code is transpiled to JavaScript?

Could you tell me exactly why am I required to import React here?


You're correct, the code transpiled by Babel will use React.

You can check for yourself using the "try it out" feature of the Babel website to see what your code will be transpiled to.

In your case, you'll get

"use strict";

module.exports = React.createElement(
    { path: "/", component: App },
    React.createElement(IndexRoute, { component: Home }),
        { path: "/repos", component: Repos },
        React.createElement(Route, { path: "/repos/:userName/:repoName", component: Repo })
    React.createElement(Route, { path: "/about", component: About })

As you can see, React.createElement is called multiple times.