Jacob Mason
Jacob Mason

Reputation: 1395

Moving react into seperate component files without Node

I'm not using Node, how do move my react code (jsx) which is currently in a text/babel script tag into separate component files? I have tried moving them and then referencing them in the html file but as soon as it hits the first bit of HTML it throws a syntax error, I have tried both .jsx and .js extensions of the file and when I include it I give it the script type of text/babel.

<script src="components/nav.jsx" type="text/babel" ></script>
<script src="components/map.jsx" type="text/babel" ></script>
<script src="components/app.jsx" type="text/babel" ></script>

Upvotes: 0

Views: 768

Answers (2)

Dmitriy Nevzorov
Dmitriy Nevzorov

Reputation: 6078

Jim Nielsen is right, however it is considered to be a bad practice to expose parts of you code to a global scope and to transpile JSX in the browser. Instead you should consider to use some building system like Webpack.

This way you would be able to use es2015 import syntax to import components from one file to another, bundle everything in one file and much more additional benefits like code minification, sourcemaps, livereload etc.

Setting up React for ES6 with Webpack and Babel

Using React with Webpack Tutorial

Related issue

Upvotes: 0

Jim Nielsen
Jim Nielsen

Reputation: 243

If you are transforming your JSX in the browser, you would have to attach each component to the window object.

As an example:

var Nav = React.createClass({ ... });
window.Nav = Nav;

Or more tersely:

window.Nav = React.createClass({ ... });

Upvotes: 1

Related Questions