Getting Started with React
(updated)
What is React ?
React is a Javascript Library to build HTML User Interfaces.
To summarize,
- React handles only the view layer
- So not like Ember, Angular or Backbone
- But it is not just an HTML templating engine
- So not like Handlebars
- It breaks monolithic HTML into components
- Each component is a combination of HTML template and Javascript code
- Written in JSX and compiled into JavaScript while building
- Each component receives a state and data and the view is rendered, so functionally it is standalone
- Components makes it easier to manage the code
- No need of long monolithic Javascript file
- 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.
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
- Changed
id
of the defaultdiv
element - Changed element
id
in index.js - Removed default
<App />
component in render code - 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
div
myApp
is rendering an HTML tagh1
with text ‘Hello World’div
myAppMain
is rendering a React component defined in src/App.js and included by the statementimport App from './App'
in src/index.js