Journey into React Part 2: Creating your first React App

In part 1 of our journey into react we got our windows work environment set up; we installed ConEmu to set up a pretty windows console, the text editor Atom.io to improve our coding experience, and then from within that console we installed Node.js and git. After that we learned how to navigate using the command line, and we created our project directory, and initialized our project with the npm init command. Lastly, we got a feel for how installing dependencies works by installing React itself.

In this part of our tutorial we'll get a working development server set up, and our first hello world app to display in the web browser. To do this we are going to install several new dependencies, set up our webpack.config file, and of course get our first taste of programming in React. So let's dive right in!

If you'd like to review only the code for this tutorial, you can find it on it's own branch on my GitHub.


Let's start with something familiar

Let's work first with some basic HTML to get us warmed up, and the easiest part out of the way. We're going to make the index.html file that our app will be mounted into. In your console, navigate to the root folder of your project and create the index.html file. It's important that you keep the extensions in mind when making these files as there will be multiple different index files down the road.

$ echo.>index.html

Setting up the index.html is pretty straight forward and follows the conventions of the language that you're already familiar with. So make you html, head, and body. Inside the body, you're going to create an empty div with a unique id:

<!DOCTYPE html>  
<html>  
  <head>
    <title>Journey into React</title>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>  

This div is going to be where we'll mount our application, which we'll get to a little bit further on. For now, save this file and let's get to making our first component.

Creating our first component

React is made up of blocks of code called components. This is one of the many things that makes React such a powerful language for application development. We are able to create different parts of the program independently of each other, then call them only when we need them. This is also great for organization, working in a team, scalability, and debugging.

The first component that we are going to make is going to be the primary one, the one that all other components are mounted into. Our app.js component should be placed in its own directory, which we'll do right now. By convention, you'll want to start with a src directory, and inside that your components directory, where you'll make your app.js file - like so:

$ mkdir src
$ cd src
$ mkdir components
$ cd components
$ echo.> app.js

Now that we have our file made, let's import React so that we can start working with it. At the top of your app.js file add:

import React, { Component } from "react";  

Not only can we import just the resources we need, but we can also pick and choose which functions from that resource to bring into our file. That's what we did just now - we imported the Component function from the react dependency that we installed earlier. This will save us some valuable space in the next part of our code, where we will actually create our component, and share it with the rest of program:

export default class App extends Component {  
  render() {
    return (
      <div>
        Hello World
      </div>
    );
  }
}

There's a lot going on here, so let's break it down. First, we are creating a Component with the function we imported from React, and we're exporting it as a default class with the name App. Now anything inside this object will be be called when we import it into our other components.

So what did we create here? Inside our render() function we are going to return a div with the contents "Hello World". Easy as that! It might feel weird at first writing our HTML inside JavaScript, but you'll get used to it pretty quickly. It's incredibly powerful to be able to mix our JS and our HTML, as we'll be able to call variables, and perform logic on what our clients are seeing on their screen.

We are able to do this because of something called webpack, and some particular settings we'll implement below. But first, let's take it one step at a time and now call this component to the screen so we can see it.

Rendering our components with ReactDOM

It's time to call in our next dependency. In your console, install ReactDom and save it, like so:

$ npm install react-dom --save

After a few moments, you'll have the react-dom module installed and saved to your package.json file so that others can use your application without you transferring your node_modules file. By simply typing npm install from the root of your application, npm will install all the dependencies in your package.json file.

Alright, so next let's create a new file in our src directory named index.js.

$ echo.> index.js

Then let's make the imports that we'll need so that everything works:

import React from 'react';  
import ReactDom from 'react-dom';  

Also, we'll want to import the component we just built, so import that as well. Notice that with the component we built, we want to include the relative file path to it:

import App from './components/app';  

Let's tell our application to render our component into the #app element we made on our index.html file.

ReactDom.render( <App />, document.querySelector('#app'));  

This little bit of code here is telling your clients screen to render the App component (noted by the tags we put on either side of it) inside a document element with the id of app.

Now we're almost there. We've created our webpage itself, our app component which we then imported it into our index.js file. We've told index.js to render our app in the webpage. Next we'll set up our server so that we can view our application.

Creating a local development server with Webpack

First things first, we've got some more dependencies to install:

$ npm install webpack webpack-dev-server --save-dev

You'll notice I did something a little different here. We've told npm to install two different packages, and save them to a special list of dependencies in our package.json file that we'll need only for development.

Webpack is one of the most complicated, yet most important part of our application. It's a module bundler, which means it takes all of the dependencies we're using, all of our static assets, and bundles them together into one minified file that we then serve our client. It reduces transfer sizes, and has some pretty incredible features that are invaluable, such as "loaders".

Remember when we were writing HTML inside our JavaScript? It's through the use of loaders inside webpack that we are able to do this. A loader is an extension of webpack that preprocesses our code and converts it into JavaScript. We are going to use a large number of loaders called babel in our application to set up our next file: webpack.config.js. Navigate to your root directory and create it:

$ echo.>webpack.config.js

Now before we go any further let's get babel and all it's additions installed. This might take a few minutes, but sit tight, we only have this one more file to write before we get to see all of our hard work in action!

I would recommend copying the below code into your package.json file to save yourself some time. It should go right above your webpack devDependencies, like so:

  "devDependencies": {
    "babel-core": "^6.7.6",
    "babel-loader": "^6.2.4",
    "babel-plugin-add-module-exports": "^0.1.2",
    "babel-plugin-react-html-attrs": "^2.0.0",
    "babel-plugin-transform-class-properties": "^6.3.13",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-preset-es2015": "^6.3.13",
    "babel-preset-react": "^6.3.13",
    "babel-preset-stage-0": "^6.3.13",
    "webpack": "^1.13.0",
    "webpack-dev-server": "^1.14.1"
  }

Now that we have all of those in there, we can save it and run npm install to install them all for us. We are preemptively installing a few of these for future use. They all convert the array of programming languages in our application into JavaScript so that it works properly.

After those are all installed, open your webpack.config.js file and define the webpack variable like so:

var webpack = require('webpack');  

Now let's configure our webpack file. It's going to look a bit complicated, but stick with it, and we'll talk about it more below:

module.exports = {  
  context: __dirname,
  entry: "./src/index.js",
  module: {
    loaders: [
      {
        test: /\.js|.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-0'],
          plugins: ['react-html-attrs', 'transform-class-properties', 
                     'transform-decorators-legacy']
        }
      }
    ]
  },
  output: {
    path: __dirname,
    filename: "bundle.js"
  }
};

Okay, so there's a few things going on here. Let's start at the entry: object, it's here that we're telling webpack what to bundle for us. It's going to read this file, take all of it's dependencies (and all of their dependencies), apply our loaders, then compress them, and output them as a single file. This file is defined as bundle.js in our output: object, and it's output path: is our parent directory.

Now for the loaders. Loaders can be complex, and have a great number of options, parameters, and plugins that we can use with them, so unfortunately that is something we're going to want to get into in more depth later. For now, take a look at the one we have typed up here.

Basically, what it's saying is that we are going to look for ( or test:) any files that end in the js or jsx extension, with the exception of (exclude:) anything in our node_modules folder, and then apply the babel-loader to them. The babel-loader itself then takes some presets and plugins that will make sure we catch all the HTML we've written and convert it into JavaScript.

Whew! That was a lot, but as you continue to work with and see webpack configuration files, they will begin to make more sense. We only have one last thing to do before we see our "Hello World" greet us on our web browser.

If you want to read more about Webpack take a look at my other tutorials here.

Add a dev script, and start our server

Before going any further we have to add one last thing to our index.html file. We told webpack that we wanted to output our application in a minified file called bundle.js, so we better get that pulled into our web page. In the body of our html (in our index.html file) add the following:

<script type="text/javascript" src="bundle.js" charset="utf-8"></script>  

The great part about the webpack-dev-server is that it not only it creates a local server for us to view our project on, but it also allows it be edited in real time. We won't have to stop the server and start it again to view what our changes have done, it will do all of that for us.

Technically we could do this and run our application right this second by typing in this monster of a command into our console:

$webpack-dev-server --inline --hot

But, who wants to do that every time they want to start their server? Nobody does, so let's make it much easier. Open your package.json and near the top you should see a "scripts" object with a "test" option within it. Erase it, and replace it with this:

"dev": "webpack-dev-server --inline --hot"

Now, every time we type npm run dev it'll call that line of code, starting our server and getting us ready for development. We can also type in webpack to create our bundle.js file. We would do this if we were say, deploying our app.

Finally, we've reach the moment of truth! Time to open your browser, navigate to localhost:8080 and start our server with npm run dev. Webpack, by default will always serve our application to port 8080. With any luck, and of course all of your hard work, you should see the simple tiny words "Hello World" displayed in your browser.

You've done it! You've officially created your first React application. Granted it doesn't do much and it took a long time to get those simple words up on a single web page, but it's ready to be scaled up and built upon. You and I will begin doing that in the next tutorial where we'll implement routing so we can change pages, our navigation bar, and add Sass styling!

If you have any questions feel free to leave them below and until next time, happy coding!

Part 3 is available - read it now!

David Meents

React.js developer, web designer, and business owner.

Subscribe to David Meents

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!
comments powered by Disqus