Webpack for react sub apps

Webpack is used to pre-compile your react component into ES5 so that it can be recognised by browsers. But what if you are webapp is hybrid and react is taking over only small portion of your webapp.

Lets suppose you have two react components, lets call them app1 and app2. Both will take over different div tag on two different pages on your website.

In this case, you can use following webpack code to precompile both of them.

var webpack = require('webpack')  
var path = require('path')

module.exports = {  
    entry:{
        app1: './src/app1.js',
        app2:  './src/app2.js'
    },
    output:{
        path: path.join(__dirname, "public/build"),
        filename: '[name].js'

    },
    devtool: '#source-map',
    module:{    
        loaders: [
            { 
                test: /.jsx?$/,
                exclude:/(node_modules)/,
                loader: 'babel-loader',
                query:{
                    presets:['react','es2015']
                }
            }
        ]

    }
}

This will create app1.js app1.js.map for app1 and app2.js app2.js.map for app2 at the destination folder.

This is working fine for me, please let me know if you run into any issues while using this.

Making server request in React Components using Axios

Axios is Promise based HTTP client for the browser and node.js. This library can be used in react component to fetch data from RESTful APIs.

Installation
$ npm install axios --save
Example
import React, { Component } from 'react'  
var axios = require('axios');  
...
        axios.get('/api/family')
            .then(response => {
            console.log(response);
            console.log(response.data);
            this.setState({
              family: response.data
            });

            console.log("family :" + this.state.family);

            })
          .catch(function (error) {
            console.log(error);
          })
...
Use of arrow function

Arrow function does not attach ‘this’ to current object and hense old this is preserved. This is needed to update state and get it reflected on rendered object.

Sample project

Please refer to this Github repo for complete code
https://github.com/conquistadorjd/react-05-mysql-api

Live project.

Please refer to following heroku site for live demo
https://react-05-mysql-api.herokuapp.com/

Working with react-router-dom

react-04-router

React Router has been broken into three packages: react-router, react-router-dom, and react-router-native. For webpages you need to use react-router-dom
and for mobile apps you need to use react-router-native. react-router is exported in both of these components.

Installation
npm install --save react-router-dom  

Two types of Router

*  <BrowserRouter>
*  <HashRouter>

Router components only expect to receive a single child element. To work within this limitation, it is useful to create an component that renders the rest of your application

Changes in the main component
import { BrowserRouter } from 'react-router-dom'

ReactDOM.render((  
  <BrowserRouter>
    <App />
  </BrowserRouter>
), document.getElementById('root'))
Actual routing settings.
<Route path='/aboutus'/>  
<Route exact path='/aboutus'/>  
  • When the pathname is ‘/’, the path does not match
  • When the pathname is ‘/aboutus’ or ‘/aboutus/xyz’, the path matches
  • If you only want to match ‘/aboutus’, then you need to use the “exact” prop.

I have added these changes in my layout file

<Switch>  
  <Route exact path='/' component={Home}/>
  <Route path='/aboutus' component={AboutUs}/>
  <Route path='/contactus' component={ContactUs}/>
</Switch>  
add these changes in required component. I have added these in my Navbar.js
    <nav>
      <ul>
        <li><Link to='/'>Home</Link></li>
        <li><Link to='/aboutus'>About Us</Link></li>
        <li><Link to='/contactus'>Contact Us</Link></li>
      </ul>
    </nav>

JSX Basics and Advanced Concepts

Take a look at following code from official react documentation

const element = <h1>Hello, world!</h1>;  

This is neither a string nor HTML. It is called JSX, and it is a syntax extension to JavaScript. It is recommended to use it with React to describe what the UI should look like.

It also means that JSX is not valid JavaScript. Web browsers can’t read it! That means file will have to be compiled before it reaches a web browser, a JSX compiler will translate any JSX into regular JavaScript.

Example

A basic unit of JSX is called a JSX element. Example of JSX element

<h1>Hello world</h1>  

JSX elements are treated as JavaScript expressions. They can go anywhere that JavaScript expressions can go.

const navBar = <nav>I am a nav bar</nav>;  

Attributes

JSX elements can have attributes, just like HTML elements can.

A JSX attribute is written using HTML-like syntax: a name, followed by an equals sign, followed by a value.

const panda = <img src="images/panda.jpg" alt="panda" width="500px" height="500px" />;  

You can nest JSX elements inside of other JSX elements, just like in HTML.
a JSX expression must have exactly one outermost element.
You can embed any JavaScript expression in JSX by wrapping it in curly braces.

Since JSX is closer to JavaScript than HTML, React DOM uses camelCase property naming convention instead of HTML attribute names.

Rendering of JSX element

ReactDOM.render(<h1>Hello world</h1>, document.getElementById('app'));  
  • One special thing about ReactDOM.render() is that it only updates DOM elements that have changed and this is what makes React very fast.
Advanced JSX

Syntax in JSX is mostly the same as in HTML, but there are subtle differences.

  • In JSX, you can’t use the word class! You have to use className instead.
<h1 class="big">Hey</h1>  
<h1 className="big">Hey</h1>  

This is because JSX gets translated into JavaScript, and class is a reserved word in JavaScript. When JSX is compiled, className gets translated into class.

  • in JSX for you have to include slash for closing tag. in HTML closing slash is not madatory for tags such as ‘< image>’ and ‘< br>’
  • Any code in between the tags of a JSX element will be read as JSX, not as regular JavaScript. You need to use curlt braces to inject JavaScript inJSX. The curly braces themselves won’t be treated as JSX nor as JavaScript. They are markers that signal the beginning and end of a JavaScript injection into JSX.
const pi = (  
  <div>
    <h1>
      PI, YALL!
    </h1>
    <p>
      {Math.PI.toFixed(20)}
    </p>
  </div>
);

Variables can be used as JSX element properties as well.

const pics = {  
  panda: "http://bit.ly/1Tqltv5",
  owl: "http://bit.ly/1XGtkM3",
  owlCat: "http://bit.ly/1Upbczi"
};
const sideLength = "200px";  
const owlCat = (  
  <img 
    src={pics.owlCat} 
    alt="Ghastly Abomination"
     height={sideLength}  />
);

Event Handling

JSX elements can have event listeners, just like HTML elements can. Programming in React means constantly working with event listeners.

<img onClick={myFunc} />  

An event listener attribute’s value should be a function. The above example would only work if myFunc were a valid function that had been defined elsewhere:

list of valid events can be found here

If Else

Tertiary operator

The ternary operator works the same way in React as it does in regular JavaScript. However, it shows up in React surprisingly often.

x ? y : z  

x is evaluated as either “true” or “false”.
If x is “true” tertiary operator returns y
If x is “false” tertiary operator returns z

Usage
const headline = (  
  <h1>
    { age >= drinkingAge ? 'Buy Drink' : 'Do Teen Stuff' }
  </h1>
);

JSX Conditionals: &&

.map in JSX

The array method .map() comes up often in React. If you want to create a list of JSX elements, then .map() is often your best bet.

const strings = ['Home', 'Shop', 'About Me'];

const listItems = strings.map(string => <li>{string}</li>);

<ul>{listItems}</ul>  

Learning React

React is not like Angular where many decisions are already made for you. In React, you have to make many decisions. Also, learning react means you need to learn multiple components like react-router, Redux etc.

This could be overwhelming and it could get you confused. So I decided to take a step by step approach to learn React.

Step#1 : Learning Path

  • Learn ES6 (At least overview and few concept like map and reduce)
  • What is React
  • JSX
  • Virtual DOM
  • Rendering
  • Components
  • Props
  • State
  • Event handling
  • Routing
  • Redux

Step#2 : Resources : getting started

There are tons of material and don’t confuse yourself with these. Stick to Most reliable and widely use approach and chances of distraction will be very less.

Step#2 : Resources : advanced (to be updated)

This is no way complete list and I will keep updating it as and when I find relevant material. If you have come across any good material, please let me know.

Adding React code highligher to Sublime 3

When I started using sublime 3 for react, code highlighter was not working properly. File was recognised as JavaScript but due to JSX syntax colour highlighter got screwed up as you can see in below screenshot. Anything coming after first closing JSX tag is not recognised properly as ‘/’ is not escape character.

I tried to find about plugins but information available was very user freindly. Please follow following steps to add syntax highliter

Step#1
Got to Package control and copy requited python code.
For sublime 3 copy following code

import urllib.request,os,hashlib; h = 'df21e130d211cfc94d9b0905775a7c0f' + '1e3d39e33b79698005270310898eea76'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://packagecontrol.io/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by)  

Step#2
Go to View–> Show Console and it will open console in sublime text window.
Alternatively you can press Ctr+~ to open same window.
Now paste code copied in above step and hit enter.

Step#3
Go to Preference–>Package Control
OR press Ctr+Shift+P
and Select Package Control:Install Package

Step#4
This step will open a pop up window. Please type required package name in the window. e.g. I wanted to install ‘babel-sublime’ as this handles react code highligter as well.

Step#5
You are not done yet.
Now go to View–>Syntax–>Open all current extensions as..–>Babel–>JavaScript(babel)

And here is the result.

If you compare this with first screenshot, you can see JSX code is highlighted properly after installing and activating ‘Babel-Sublime’

Please do let me know if you run into any issues.

react js router tutorial

After getting started with basics of react, I was looking for how to do routing using react. Most widely use packages are react-router, react-router-dom. Here is simple code that will get you started using react-router-dom.

Step#1
Create a simple react app using creae-react-app command. You can refer to getting started with react post to get you stared.

$ create-react-app todolist

Step#2
Here is my index.js file edited for router.

import React from 'react'  
import ReactDOM from 'react-dom';  
import { BrowserRouter, Route } from 'react-router-dom'  
import Layout from './Layout';  
import Header from './Header';  
import Footer from './Footer';

class App extends React.Component {  
  render() {
    return (
        <div>
          <h1>hello new </h1>
        </div>
    )
  }
}

class About extends React.Component {  
  render() {
    return (
        <div>
          <h1>This is About Page</h1>
        </div>
    )
  }
}

//export default App

ReactDOM.render((  
<BrowserRouter>  
    <div>
      <Route exact path="/" component={App} /> {/* Note-1 */}
      <Route path="/header" component={Header} />
      <Route path="/footer" component={Footer} />
      <Route path="/Layout" component={Layout} />
      <Route path="/About" component={About} />
    </div>
</BrowserRouter>

),
  //<App />,
  document.getElementById('root')
);

Please find below sample file for Header. Footer and Layout files will be similar.

import React from 'react';

class Header extends React.Component {  
  render() {
    return (
      <div >
        <h1>This is Header</h1>
      </div>
    );
  }
}

export default Header;  

As per GitHub issue response, if you are using react-router-dom, you done need to import react-router (at least 99.99 % of time).

Reference Posts:
https://stackoverflow.com/questions/42984597/multiple-nested-routes-in-react-router-dom-v4

https://stackoverflow.com/questions/43008036/the-prop-history-is-marked-as-required-in-router-but-its-value-is-undefine

How reactdom render works

Let us look at how react web application works. Please find the source code for very basic application at below location.
https://github.com/conquistadorjd/myreactapp

Let us look at index.js file.

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

class App extends React.Component {  
   render() {
      return (<div>  
                <h1>You are on website techtrekking.net</h1>
                <ul>
                    <li >FIrst</li>
                    <li>Second</li>
                    <li>Third</li>
                  </ul>
              </div>)
   }
}

ReactDOM.render(<App />, document.getElementById('root'));  

Now let us look at each elements separately:

var React = require('react');  
  • It saves a JavaScript object into your file. This object contains methods that are needed to make React work, such as React.createElement and React.createClass
  • when a JSX element is compiled, it transforms into a React.createElement() call. e.g. React.createElement
var ReactDOM = require('react-dom');  
  • The methods returned by require(‘react-dom’) are for interacting with the DOM. e.g. ReactDOM.render
  • This object contains methods that are concerned with DOM interaction, such as ReactDOM.render
ReactDOM.render(<App />, document.getElementById('root'));  
  • ReactDOM.render is the most common way to render JSX
  • It takes a JSX expression, creates a corresponding tree of DOM nodes, and adds that tree to the DOM.
  • ReactDOM.render()’s first argument should evaluate to a JSX expression, it doesn’t have to literally be a JSX expression. The first argument could also be a variable.
  • Second argument is the DOM where this will be rendered.

react JSX| Basics

JSX Introduction

JSX is a syntax extension to JavaScript. It is used with React to describe what the UI should look like. JSX might seem like template language, but it comes with the full power of JavaScript.

Here is the sample code. We will explore each feature in detail in below article:

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

var websiteName = 'techtrekking.net';  
var newStyle = { color:'blue'};

var myList = (<div>  
                <h1>You are on website {websiteName}</h1>
{// this is comment }
                <ul>
                    <li style={newStyle}>FIrst</li>
                    <li>Second</li>
                    <li>Third</li>
                  </ul>
              </div>)

ReactDOM.render(myList, document.getElementById('root'))  

Important Points

  • JSX is a syntax extension for JavaScript. It was written to be used with React. JSX code looks a lot like HTML.
  • A basic unit of JSX is called a JSX element.
  • JSX code can’t be ready by browser and hence it needs to be compiled before the files reaches a web browser, a JSX compiler will translate – any JSX into regular JavaScript.
    It’s similar to writing bits of HTML, but inside of a JavaScript file.
JSX Element Definition
  • JSX element can be saved in a variable, passed to a function, stored in an object or array.
var h1 = <h1>Hello world</h1>;  
Attributes in JSX
  • A JSX attribute is written using HTML-like syntax: a name, followed by an equals sign, followed by a value. The value should be wrapped in quotes, like this:
var title = <h1 id="title">Introduction to React.js: Part I</h1>;  
var panda = <img src="images/panda.jpg" alt="panda" width="500px" height="500px" />;  
  • HTML tags are always using lowercase tag names, while React components starts with Uppercase.
  • Since JSX is JavaScript, identifiers such as class and for are discouraged as XML attribute names. Instead, React DOM components expect DOM property names like className and htmlFor, respectively.
Multi-line JSX
  • You can nest JSX elements inside of other JSX elements, just like in HTML.If a JSX expression takes up more than one line, then you should wrap the multi-line JSX. i.e. opening and closings should be of same tag
var myList = (<div>  
                <h1>You are on website {websiteName}</h1>
                <ul>
                    <li style={newStyle}>FIrst</li>
                    <li>Second</li>
                    <li>Third</li>
                  </ul>
              </div>)
Using JavaScript in JSX
  • JSX is written in JavaScript file but if you need to use JavaScript variale in JSX it needs to be enclosed in curly braces “{}”
...
var websiteName = 'techtrekking.net';  
...
<h1>You are on website {websiteName}</h1>  
...
Comments in JSX
  • While writing comments we need to enclose curly braces around them “{}”.
{// this is comment }

create react app | Getting started with react

Create React App is the best way to start building a new React single page application. It sets up your development environment so that you can use the latest JavaScript features, provides a nice developer experience, and optimizes your app for production.

$ npm install -g create-react-app
$ create-react-app todolist

If you are using older version of Node.js and npm you might get following error message.

I am also using Ghost blogging platform so I need to use 4.8 LTS version of Node.js so I will keep my current version, but if you dont have any dependency like above, please update to latest stable version.

$ create-react-app myreactapp
Creating a new React app in /home/user/code/nodejs/myreactapp.

You are using Node v4.8.3 so the project will be boostrapped with an old unsupported version of tools.

Please update to Node 6 or higher for a better, fully supported experience.

You are using npm 2.15.11 so the project will be boostrapped with an old unsupported version of tools.

Please update to npm 3 or higher for a better, fully supported experience.  

Once installation is complete got to the newly created folder and start the application.

$ cd myreactapp
$ npm start

This will start development server and it will open a webpage on your default browser at following location.

http://localhost:3000/

This will create file structure as below: index.html provides basis div elements and index.js is primary react file which renders required components in index.js

├── package.json
├    (Node.js file structure)
├── package.json
├── public
│   ├── favicon.ico
│   └── index.html
├── README.md
└── src
    ├── App.css
    ├── App.js
    ├── App.test.js
    ├── index.css
    ├── index.js
    └── logo.svg