React.js | Advanced Todo App from scratch for beginner | Bootstrap | In a nut shell

Introduction

It is a good practice to follow community standards while developing softwares. It has some major pros like

  • Its easier to understand and debug/maintain software
  • quicker to get help when needed from community
  • It will lower development cost [Money and Time]

We will be taking the convention used by this project into consideration. react-slingshot

Initialize

Make a dir called ‘todo‘ and initialize a node.js app.

$ mkdir todo
$ cd todo
# You will see package.json, edit the details in the file
$ npm init
# Output
Wrote to /home/john/projects/reactjs/todo/package.json:

{
 "name": "todo",
 "version": "1.0.0",
 "description": "",
 "main": "index.js",
 "scripts": {
 "test": "echo \"Error: no test specified\" && exit 1"
 },
 "keywords": [],
 "author": "",
 "license": "ISC"
}

Tools to be used

  • Webpack
    • Its like bundler, manages your dependencies
  • Webpack dev server
    •  open up your browser to http://localhost:8080
      • You can change the port number
      • HTTP server will serve your application in localhost
    •  HotModuleReplacementPlugin
      • hot reloading of changes JS assets
      • No need to reload the page; changes will reflect as soon as you save the source files.
  • Babel
    • To convert ES6 syntax to ES5 [Older JS]

Setup dependencies

Full-time dependencies

These are dependencies you are gonna need during production as well

# Install libs and update the file package.json
$ npm install --save react react-dom

Development Dependencies

$ npm i -D -S babel-core babel-loader babel-preset-es2015 babel-preset-react react-hot-loader webpack webpack-dev-server

Note: i –> install, -S –> --save, -D –> --save-dev

--save actually allows npm to update the package.json with the dependency info. Checkout the changes in the file package.json using git.

Also, gonna need to install webpack and webpack-server globally in the system if you have not already.

Why to install webpack, webpack-server globally?

See this answer

Config Webpack

$ subl webpack.dev.config.js # open this file in sublime text; Open in any text editor

Point is, create this new file and fill with webpack configs.

// todo/webpack.dev.config.js
// Note: This file contains ES5 syntax
//  ES6 syntax can also be used
// ------------------------------------------------------

var webpack = require('webpack');

// The path module provides utilities for working with file
//  and directory paths. It can be accessed using:
// See: https://nodejs.org/docs/latest/api/path.html
var path = require('path');

module.exports = {
  devtool: 'inline-source-map',
  entry: [
    'webpack-dev-server/client?http://127.0.0.1:3000/',
    'webpack/hot/only-dev-server',
    './src/app.jsx' // If No Filename (./src/), its gonna look for `index.js`
  ],

  // Production details
  output: {
    // When compiled for production, output file location
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js' // Its convention to use this name
  },

  // Bundle lookup dir for included/imported modules
  // By default, bundler/webpack with search here for the scripts
  resolve: {
    modulesDirectories: ['node_modules', 'src'],
    extensions: ['', '.js', '.jsx']
  },

  module: {
    loaders: [
      {
        test: /\.js[x]?$/,
        exclude: /node_modules/,
        loaders: ['react-hot', 'babel?presets[]=react,presets[]=es2015']
      }
    ]
  },

   // Server configs 
   // See https://webpack.js.org/configuration/dev-server/
   devServer: {
     port: 3000,
     contentBase: './src' // Location where index.html is supposed to be present
   }, 

  plugins: [
    new webpack.HotModuleReplacementPlugin(), // For live reloading
    new webpack.NoErrorsPlugin(), // Makes sure Webpack will not compile if Errors

    // prints more readable module names in the browser console on HMR updates
    new webpack.NamedModulesPlugin(),
  ]
};

What is a loader in webpack?

Loaders are transformations that are applied on a resource file of your app. They are functions (running in node.js) that take the source of a resource file as the parameter and return the new source.

For example, you can use loaders to tell webpack to load CoffeeScript or JSX. Also, .scss file can be processed using sass loaders for webpack.

Configuration

You can bind loaders to a RegExp via configuration:

// todo/webpack.config.js
{
    module: {
        loaders: [
            { test: /\.jade$/, loader: "jade" },
            // => "jade" loader is used for ".jade" files

            { test: /\.css$/, loader: "style!css" },
            // => "style" and "css" loader is used for ".css" files
            // Alternative syntax:
            { test: /\.css$/, loaders: ["style", "css"] },

            { test: /\.scss$/, loaders: ["style-loader", "css-loader", "sass-loader"] },
         ] 
     } 
}

Main Page

Create index.html file that webpack will load.

$ mkdir src
$ touch src/index.html

# Put some content in it

See this file src/index.html

// src/app.jsx 
let welcome_message = 'Hello this is my first react app';
console.log(welcome_message);

Actually, if the file index.html was on the root dir, webpack-dev-server would have picked it by default. But, we changed the location, we need some extra thing to get going.

   // Server configs 
   // See https://webpack.js.org/configuration/dev-server/
   devServer: {
     port: 3000,
     contentBase: './src' // Location where index.html is supposed to be present
   },

Test Drive

Update the script config in package.json file like

"scripts": {
  "start":       "webpack-dev-server -d --config webpack.dev.config.js --progress --colors",

  # These items are need for production deployment  
  "prod":        "NODE_ENV=production node server.js",
  "build":       "webpack --config webpack.prod.config.js -p --progress --colors",
  "postinstall": "webpack --config webpack.prod.config.js --progress --colors"
},

Run the server

$ npm start
# Webpack will compile the bundle.js file; it will not be 
#  physically available on the disk yet; only in production

Open http://localhost:3000/ and you can see the following output in the Browser console.

[HMR] Waiting for update signal from WDS...
Hello this is my first react app

Congrats, Your application is set up !!!

git setup

Initialize git in your dir and add node_modules into .gitignore file.

# Logs
logs
*.log*

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directory
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
node_modules

# dist folder
dist

# IDEA/Webstorm project files
.idea
*.iml

# VSCode metadata
.vscode

# Mac files
.DS_Store

# Skip the build file; you might want to rebuild in deployment server
/src/bundle.js

Complete ToDo App

Here is the link to the github repo of this project.

List Item

See this item-list.jsx

Delete Item

See this pull request to understand how delete works.

Setup Bootstrap

See this pull request to understand how bootstrap is integrated in React.js apps.

Pros of Component based model in React.js

  • When you design your app with large number minute components, it’s faster to address the state change in DOM.
    • Only the component whose state is recently updated using setState method is re-rendered; no effects whatsoever to other objects.
    • In traditional apps, one would have to reload the whole page.

Deployment to Heroku

See this post for deployment related stuff

Some useful links

http://ditrospecta.com/javascript/react/es6/webpack/heroku/2015/08/08/deploying-react-webpack-heroku.html

http://revelry.media/tech-talk/2016/2/15/getting-a-simple-react-app-on-heroku

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s