How to start using React on the simple html page

React is a great JavaScript library for creating interfaces. Some people always will say that this is a framework, but it’s not and I’ll show you why. What if I want to use React and JSX in a normal index.html file with no npm or webpack in sight? And that’s possible. Without using of npm, react-router, redux and webpack React is just as simple JS library as jQuery. To prove this we will write simple React counter with using CDN. Let’s start!

See the Pen React CDN Usage by Alex (@forest-black) on CodePen.0

We will create the simplest React app – Counter. First of all, we need to create the div with the id app within body tag where all our React app will be deployed.
<div id="app"></div>
Secondly, we have to add script tags that will add React and ReactDOM files
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
// React main file
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
// ReactDOM file that is used for virtual DOM creating and faster work
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
// Babel file is used for reading React code by computer
Now, we can add some React code in the script html tag right after adding React, ReactDOM and Babel, but we to tell babel to compile it by adding attribute type=”text/babel” , not like we do regularly type=”text/javascript”
class App extends React.Component {
	constructor(props) {
		super(props)

		this.state = {
			count: 0,
			changed: ''
		}

		this.increment = this.increment.bind(this);
	}
	
	increment() {
		this.setState({ count: this.state.count + 1, changed: true });
	}

    render() {
        return (<div>
        <div>Count: {this.state.count}</div>
        <button onClick={this.increment}>+</button>
        <div>{this.state.changed ? 'State is changed' : ''}</div>
    	</div>);
    }
}
ReactDOM.render(
    <App />,
    document.getElementById('app')
);
Now our simple SPA on React is built in one html file. Is this a good idea? I think no, but 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. It’s as simple as Vue.js to add React and to use it. Now that you are off to a great start, I hope you will enjoy learning React as much as I did. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *