To Do: Create Your First React Application - Part I
React is a JavaScript library that is primarily responsible for handling the “view” component of a JavaScript single-page application. As it describes itself of the React homepage…
Lots of people use React as the V in MVC. Since React makes no assumptions about the rest of your technology stack, it’s easy to try it out on a small feature in an existing project.
React’s focus, first and foremost, has to do with rendering dynamic UIs in a manner that is visually appealing to the user. It is flexible enough that it can be used in a diversity of capacities and contexts. We have looked at React in previous entries. In what follows we will look at creating an introductory application using React and React related tools and libraries. One of the more ubiquitous tutorial applications that developers build when learning a new language or framework is the TO DO (To do) app. In terms of prevalence, it is probably second only to the “Hello, World” app which has been around since the dawn of programming. But the “To Do” application is popular because it covers a lot of the basics of how a language or framework handles a number of things. There must be a way to add a new “to do” so handling user input is involved. The same is true for displaying data, editing and saving data, and changing display state when data updates. All of these things are going to be important implementations in any application.
In what follows we will create the iconic “To Do” application in React and discuss some of the inner workings as we go along. We will take a deeper look into React components and how we can add some dynamic interactivity to our React applications in response to user actions — things like clicks and entering text in a text box — and updating our views accordingly.
JSX Compilation with Babel & Browserify
As we will see, React has its own programming language called JSX. It has been described as sort of like a mixture of JavaScript and XML and it is React’s own special easy-to-read abstracted syntax. JSX is not required to create React applications and you can write your React components in native JavaScript if you prefer. Because browsers do not natively understand JSX in order for your react application to run JSX needs get converted to native JavaScript.
The React website suggests that you utilize tools like Babel and/or Browserify (both of which run on Node.js). Babel is what is known as a transpiler. It mostly functions as a tool that takes code written in ECMAScript 6 (ES6) and converts it to ES5. As of 2015 this is still necessary because support for ES6 across all browsers is not widespread yet. Until support for ES6 is implemented across all browsers, tools like Babel will still be needed. Although many people think of Babel primarily as an ES6 to ES5 transpiler, Babel also comes with JSX support as well. You can merely run the Babel transpiler on your JSX files and they will be converted to native JavaScript that will be recognized by any browser circa 2015.
Browserify allows for Node.js style module loading in your client-side JavaScript. Like with Node, it allows you to import code in certain JavaScript files into other JavaScript files for better organization of your code.
Task Runners / Module Bundlers
For our sample code, we will be using task runners to handle our JSX conversion to native JavaScript. You may have heard of task runners like Grunt or Gulp, or module bundlers like webpack. We will be using webpack because it has, at least for the time being, become the utility of choice among the React community. If you are not entirely familiar with JavaScript task runners it would definitely be worthwhile to read the webpack documentation (or watch a few videos) on what it is and why you would want to use it. The more recent versions of React essentially require you to set up your tools before you work with JSX in React. In previous versions of React there was an easy extra <script> tag that you could add in your HTML to make it easy to implement JSX. However this has since been deprecated. If this seems daunting and you are already feeling overwhelmed, not to worry! We will walk through how to set everything up before we dive into React coding.
Setting Up
To start we need to set up our package.json and webpack.config.js files so that we can set up our tools to do JSXcompilation to native JavaScript. Create a new directory and then create a package.json file and add the following…
{
"name": "React",
"version": "0.0.1",
"description": "A React application...",
"license": "MIT",
"repository": {
"type": "",
"url": ""
},
"homepage": "http://www.9bitstudios.com",
"scripts": {
"start": "webpack-dev-server --progress"
},
"dependencies": {
"react": "15.3.0"
},
"devDependencies": {
"webpack": "1.13.1",
"webpack-dev-server": "1.14.1",
"babel-core": "6.13.0",
"babel-loader": "6.2.4",
"babel-preset-es2015": "6.13.0",
"babel-preset-react": "6.11.1"
}
}
Next, in this same directory, create a webpack.config.js file and add the following…
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: __dirname + "/src/App.js",
output: {
path: __dirname + "/dist",
filename: "App.js"
},
watch: true,
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query:{
presets: ['es2015', 'react']
}
}
]
},
devServer: {
colors: true,
inline: true
},
plugins:[
new webpack.optimize.UglifyJsPlugin(),
]
};
After this, let’s open a command prompt and run the following…
$ npm install
to install all of our modules that we will need for compiling ES6 and JSX. And that is all there is to it. Now that we have our tools installed and configured, we can dive into writing our application.
Writing a “To Do” Application
So let’s get started creating our “To Do” app. We will start out by creating our index.html file…
<!DOCTYPE html>
<html>
<head>
<title>React</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="content"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react-dom.js"></script>
<script type="text/javascript" src="dist/App.js"></script>
</body>
</html>
As we can see, we are going to include App.js, which will be a file that we generate in our task runner. Note too we are creating a
Next, create a folder called “src” and create a file called App.js in this folder. For this tutorial we are going to be breaking our components up into different modules so in our App.js file all we need to add for now is the following.
import {react} from 'react';
In the same directory as your App.js file, next create a file called “Todo.js”. In this file, we are going to need to create a React component/class that will represent each individual “to do.” Add the following code to this file…
import {react} from 'react';
class Todo extends React.Component {
render() {
return(<div>I am a to do</div>)
}
};
Pretty straightforward. This should look familiar as it is similar to our other earlier examples.
Now what we’re going to do is import this module into our App.js file. How do we do this? In our App.js file we just need to add the following…
import {react} from 'react';
import {Todo} from './Todo';
This will tell our code to import the “Todo” module from the “Todo” file relative to where “App.js” is located. With module loading in ES6 you can omit the “.js” from the file when you are importing modules.
So we are definitely well on our way but if we were to run this code as it is right now we would get an error. Why is this? Well, because we are importing a module from our “Todo.js” file we need to specify what this file exports. To do this we need to add the “export” keyword in front of what we want to make available from the “Todo.js” file. Thus, we need to change our code in our “Todo.js” file to the following…
import {react} from 'react';
export class Todo extends React.Component {
render() {
return(<div>I am a to do</div>)
}
};
Notice how we have added the “export” keyword in front of our class. Now there is something that can be imported from the “Todo.js” file. We will get into more complex combinations of what various files can export and import later on, but for now this simple example shows the basic setup of how it is done.
Now in our App.js file add the “render” method so we can confirm that everything is working…
import {react} from 'react';
import {Todo} from './Todo';
ReactDOM.render(<Todo />, document.getElementById('content'));
Let’s build our App.js file by running “webpack” by opening up a terminal window typing the following…
$ webpack
Doing the above will build the App.js file and place it in our “dist” folder. Now if we open up another terminal window and run our server with…
$ npm start
and we go to http://localhost:8080 in our browser, if all has gone well we should be able to see the text “I am a to do.”
Component Composition
For our application we will be rendering a list of “to do” items inside of our “to do” list. Thus, we will also need to create a component that represents our “to do” list. So create a “TodoList.js” file in the same directory as the others and add the following code…
import {react} from 'react';
import {Todo} from './Todo';
export class TodoList extends React.Component {
render() {
return(<div>To do list here...</div>)
}
};
“TodoList” is the component that will serve as our “root” container component for our React application. It is just returning some placeholder text for now, but we will be adding more complexity to it very soon. Because the “TodoList” top-level component for this particular application, it is this one that will be the one that we want to render in our App.js file (not the individual “Todo” components). So change the code in our App.js file to the following…
import {react} from 'react';
import {TodoList} from './TodoList';
ReactDOM.render(<TodoList />, document.getElementById('content'));
Notice now how we are now rendering the “TodoList” component now and not the “Todo” components.







