DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. JavaScript
  4. Bootstrapping a React Project (Part 1)

Bootstrapping a React Project (Part 1)

Check out this comprehensive deep dive into building your first ReactJS project. This first part covers setup, routing, and internalization.

Prosper Otemuyiwa user avatar by
Prosper Otemuyiwa
·
Aug. 14, 16 · Tutorial
Like (3)
Save
Tweet
Share
7.44K Views

Join the DZone community and get the full member experience.

Join For Free

TL;DR: The JavaScript ecosystem has a plethora of libraries and frameworks for front-end development. ReactJS is one of the young and shiny new libraries on the block. Even though it's only a few years old, it has gained lots of traction from JavaScript developers around the world. One of ReactJS's selling points is the ability to easily build reusable components. Another salient point is that not only does it perform on the client side, it can also be rendered on the server side.

Why React?

ReactJS was built by Facebook to solve one problem: building large applications with data that changes over time. It utilizes the concept of the Virtual DOM that selectively renders subtrees of nodes based upon state changes. The component-based architecture that ReactJs emulates makes it incredible to work with. Components in ReactJS are self-contained views that get their data from triggered events or as inherited property from other components. There are essentially two main ways of writing components, using React.createClass and extending React.Component. Props and States in ReactJs also make it fun to work with. Learn more about the basic concepts of React here.

Using React.createClass Syntax

var HelloComponent = React.createClass({
  render: function() {
    return (
      <div className="hello">
        Hello, world!
      </div>
    );
  }
});

ES6 Way

class HelloComponent extends React.Component {
  render() {
    return (
      <div className="hello">
        Hello, world!
      </div>
    );
  }
}

ReactJS supports the use of ECMAScript 6 features. With Babel, you can write ReactJS the ES6 way, making use of classes, arrow functions and a host of other ES6 features.


// CommonJS way
var React = require('react');
var ReactDOM = require('react-dom');

// ES6 Way
Import React from 'react';
Import ReactDom from 'react-dom';

// ES5 way
var Main = React.createClass({
  render: function() {
    return (
      <div>
        The easiest way to add authentication to your app is via Auth0!
      </div>
    );
  }
});

// ES6 way
export default class Main extends React.Component {
  render() {
    return (
      <div>
        The easiest way to add authentication to your app is via Auth0!
      </div>
    );
  }
}

Let's Get Started

Bootstrapping a ReactJS project involves setting up lots of tools, and it can really be a daunting task. Thankfully there are several tools provided for developers by the community to aid in setting up your project without breaking a sweat. In this post, we'll cover tools that you should be aware of in bootstrapping your next ReactJS project.

Building a React App

The first step is to set up a development environment for your ReactJS project. Webpack, a bundler utility, and Babel are key tools here. Babel lets us write code that uses new ES6 features, and then transpiles that code into standard ES5 code that can actually run in the browser. When setting up a new project:

  • I assume Node.js and NPM is installed, run this command: npm init to create a package.json file
  • Run this command in your terminal: npm install react react-dom babel-core babel-loader babel-preset-es2015 babel-preset-react webpack webpack-dev-server --save
  • Create a webpack.config.js file. This file handles bundling all our assets, converting JSX to JS files and launching the development server. Bundling refers to combining, compiling and minimizing multiple files into just one file to be served to the client.

Note: JSX is a JavaScript syntax extension that looks similar to XML. You can write concise HTML/XML-like structures in the same file as you write JavaScript code. With Babel, JSX files can be transpiled into actual javascript code.

A sample webpack.config.js is shown below:

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');

module.exports = {
  context: path.join(__dirname, "src"),
  devtool: debug ? "inline-sourcemap" : null,
  entry: "./js/App.js",
  devServer: {
    inline: true,
    port: 3333
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015'],
          plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'],
        }
      }
    ]
  },
  output: {
    path: __dirname + "/src/",
    filename: "bundle.min.js"
  },
  plugins: debug ? [] : [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
  ],
};

The application's entry point is set at the entry. The file specified at theentry is the first component that the Web page loads. Webpack will bundle all the JS and JSX files into the file that's specified in the output object. Webpack dev server is set to inline which allows a kind of reload on the fly and the application will be served at port 3333. In the module object, we specify the Babel loader to use react and es2015 presets for convertingES6 and React code into code that the browser understands. The webpack plugins add the ability to use class properties and decorators.

Note: Babel presets are basically plugins that have been configured to do a particular task.

Hot reloading

The idea behind hot reloading is to keep the app running and to inject new versions of the files that you edited at runtime. This way, you don't lose any of your state which is especially useful if you are tweaking the UI.

Hot Reloading

(Source: Medium)

You can install hot module replacement like so:

npm install --save-dev babel-preset-react-hmre

Now, you can add it to the list of presets in the webpack.config.js file like so:

....
query: {
  presets: ['react', 'es2015', 'react-hmre'],
  plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'],
}

Another option is to install react-hot-loader and add react-hot to the loader in the webpack.config.js file like so:

...
loader: ['babel-loader', 'react-hot']
...

To make things really easy, add a start option to the scripts object inpackage.json file like so:

{
  "scripts": {
    "start": "node_modules/.bin/webpack-dev-server --progress --inline --hot",
  }
}

The code above shows we have added the --hot option. This enables the hot reloading once you start your app by running npm run start.

Routing

Routing is an essential part of any application. The most popular choice for doing this in a ReactJS application is React Router. In fact, a lot of developers consider it the official routing system for ReactJS. When you want to deal with routing, you have to install the React Router module in your project as shown below:

npm install --save react-router

A sample implementation will look like this:

import React from 'react';
import { render } from 'react-dom';
import { browserHistory, Router, Route, IndexRoute } from 'react-router'

import App from '../components/App'
import Home from '../components/Home'
import About from '../components/About'
import Features from '../components/Features'

render(
  <Router history={browserHistory}>
    <Route path='/' component={App}>
      <IndexRoute component={Home} />
      <Route path='about' component={About} />
      <Route path='features' component={Features} />
    </Route>
  </Router>,
  document.getElementById('app')
)

Routing

You actually might not need React Router. More info here

Internationalization (I18N)

There are over 7 billion people in the world. These people speak different languages. One way of making your app available to billions of people around the world is providing support for native languages in your app. In aReactJS project, you can easily achieve that with a very good and well tested library react-intl. By default, react-intl ships with the locale data for English built-in to the library's runtime. This library provides React components and an API to format dates, numbers, and strings, including pluralization, and handling translations. Oh, it supports over 150 languages!

Internationalization Translation




Continue Reading

Tomorrow, we'll continue on with part 2.

React (JavaScript library) app application Babel (protocol) Library JavaScript dev

Published at DZone with permission of Prosper Otemuyiwa, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • What Was the Question Again, ChatGPT?
  • Microservices Discovery With Eureka
  • How To Check Docker Images for Vulnerabilities
  • A Brief Overview of the Spring Cloud Framework

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: