Getting Started with React

(updated)

What is React ?


React is a Javascript Library to build HTML User Interfaces.

To summarize,

  1. React handles only the view layer
    • So not like Ember, Angular or Backbone
  2. But it is not just an HTML templating engine
    • So not like Handlebars
  3. It breaks monolithic HTML into components
  4. Each component is a combination of HTML template and Javascript code
    • Written in JSX and compiled into JavaScript while building
  5. Each component receives a state and data and the view is rendered, so functionally it is standalone
  6. Components makes it easier to manage the code
    • No need of long monolithic Javascript file
  7. Makes use of VirtualDom

Requirements


This tutorial is for React development on NodeJS. So before starting make sure that the environment has the following installed.

  1. NodeJS
  2. NPM

Installation


Please install React initialization tool globally by giving the following command in console. Use sudo if required.

> npm install -g create-react-app


Create React Application


Now create your first app by giving the command given below

> create-react-app MyReactApp

It may take a few minutes for the tool to create the minimal application and install required node modules. Once it is done,the application folder will be


To run your application


Now to run your application, enter application folder and run npm command as shown below.

> cd MyReactApp
> npm start

If the server starts successfully, console will show this

Compiled successfully!

The app is running at:

  http://localhost:3000/

Note that the development build is not optimized.
To create a production build, use npm run build.

Open http://localhost:3000/ in browser and you can see the React Application running.

Make some changes


Now let us make some minor changes to understand how things work in React.

Open public/index.html. Change id from root to myApp

Open src/index.js. Change the code to


What we have done here

  1. Changed id of the default div element
  2. Changed element id in index.js
  3. Removed default <App /> component in render code
  4. Replaced it with simple <h1> Hello World </h1>

Now refresh your browser and you can see

Some more changes


Now let us try to render the component <App /> along with ‘Hello World’. Open public/index.html again and add one more div element and set id myAppMain

Then modify src/index.js to

Here

  1. div myApp is rendering an HTML tag h1 with text ‘Hello World’
  2. div myAppMain is rendering a React component defined in src/App.js and included by the statement import App from './App' in src/index.js

Final Output


Share