How to add React to a simple html file

So you heard about javascript fatigue and using webpack makes you feel like programming may not be your thing after all?

Well, what if I told you you can use React and ES6 and JSX in a normal index.html file with no npm or webpack in sight? Yeah, I couldn’t believe it too, but adding React should be no harder than adding jQuery.

So, without further ado, let’s start with a normal index.html containing nothing more than:

<p>Hello world</p>

So far so good. Now that we have a starting page, how would one go about adding a reference to an external library? Well, using CDN is a reasonable start when experimenting with a new library. Let’s remove the p added above and replace it with the following:

<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script type="text/babel">
class Greeting extends React.Component {
render() {
return (<p>Hello world</p>);
}
}
ReactDOM.render(
<Greeting />,
document.getElementById('root')
);
</script>

Refresh the page! Nothing changed, right?

Except that you got React, ES6 and JSX by adding nothing more than a couple of external library references and then writing inline js code.


Explanation of the above code:

  • First line declares a container for our UI as a simple div with id root
  • Then three libraries are referenced: react, react-dom, and babel-standalone. First two you need to render React into a DOM and the third one enables JSX and ES6.
  • Then we get to write our code in a classical <script> block but with a twist: declare it as text/babel to enable transpilation from ES6 to ES5
  • Inside the code block we declare a simple React component that renders as a <p> tag
  • The final line of code renders the component tree (in our case just a single component) into the root element we declared in the first line.

Is this a good idea? Depends, if you just want to start learning, you can’t start smaller than that. If you want to use it in production, you might want to prebundle it, but let’s not get ahead of ourselves.

Now that you are off to a great start, I hope you will enjoy learning React as much as I did. Happy coding!