What is ReactJS ?
React it a
javascript library which is used to build user interfaces.
React is
used to build single page applications.
React
allows to create reusable UI components.
Create React App
In order
to learn about react you should set up a react environment in your machine. For
that you should have installed NPM and NodeJS in the machine.
After the
installation of NPM and NodeJS go to the folder where you want to create your
React App. Then open the command prompt and give the below command.
npx create-react-app myfirstreact
Then after
the loading is completed, go inside the project folder using the cmd by giving
the below command
cd myfirstreact
Finally
give the below command to run the React App.
npm start
Then a new
browser window will pop up your app in the browser. If not access the following
link : http://localhost:3000
The browser will be display as the following screenshot.
Getting started with React
Open the
project folder (myfirstreact) in an IDE. There is a file called “App.js” inside
the “src” folder. You may find the below code in “App.js”
import logo from './logo.svg'; import './App.css'; function App() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ); } export default App;
import './App.css'; function App() { return ( <div className="App"> <h1>Hello World...</h1> </div> ); } export default App;
Before
starting with ReactJS you should have a knowledge on:
· HTML
· CSS
· Javascript
Also it
would be better if you could have an experience with the new javascript
features introduced in ECMAScript 6 (ES6). Because React use;
·
Classes
·
Arrow
Functions
·
Variables
(let , const , var)
How does the React works ?
React
creates a Virtual DOM in the memory. Before making changes in the browser,
react manipulates the Virtual DOM.
React
changes only what needs to be changed.
What is a DOM ?
When you
open any webpage in a browser, the HTML of the page is loaded and rendered
visually on the screen.
To
accomplish that, the browser builds the Document Object Model of that
page. (It is an object oriented model of its logical structure)
The DOM of an HTML page can be represented as below;
React Components
Components are independent and reusable codes. Its purpose is same as javascript functions, but react components return HTML via a render() function.
Component name should start with an upper case letter.
There are
two types of react components. They are Class Components and Function
Components.
1.
Class
Component
classCar
extends
React.Component
{
render()
{
return
<h2>Hi, I am a Car!</h2>;
}
}
2.
Function
Component
functionCar()
{
return
<h2>Hi, I am also a Car!</h2>;
}
React Props
Props are
arguments which are passed to react components and those are passes via HTML
attributes. Props are used to pass data from one component to another.
In the
same project you created above, open the “App.js” and change the code as
follows :
import React, {Component} from 'react';
class App extends Component {
render() {
return (
<div>
<h1>Where do you live ?</h1>
<Country countryName="Sri
Lanka" />
</div>
);
}
}
class Country
extends React.Component
{
render() {
return <h2>I live in {this.props.countryName}!</h2>;
}
}
export default App;
React State
React
components has built-in “state” objects. Property values which are belong to a
component, are stored inside a “state” object. The state object may initialized
inside the constructor.
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
State
of a property can be changed as follows
;
changeColor = () => {
this.setState({color: "blue"});
}
React Lifecycle
Each react
component has a lifecycle which you can monitor and manipulate during its 3
main phases. The 3 main phases are : Mounting , Updating and Unmounting
Mounting (Putting
elements to the DOM) |
constructor() constructor(props) { super(props); this.state = {favoritecolor: "red"}; } |
Called
before anything else. Initial state and
initial values will be defined here. |
getDerivedStateFromProps() static getDerivedStateFromProps(props, state) { return {favoritecolor: props.favcol }; } |
Called
right before rendering the elements in the DOM. Sets the state object based on the initial
props. Takes state as an argument and returns the state with the changes. |
|
render() class Header extends React.Component { render() { return ( <h1>This is the content of the
Header component</h1> ); } } |
This
method is required. Outputs HTML to the DOM |
|
componentDidMount() componentDidMount() { setTimeout(() => { this.setState({favoritecolor: "yellow"}) }, 1000) } |
Called
after the component is rendered. |
|
render() method is required and always be
called while other methods are optional will be called only when you define
them. |
||
Updating (component
is updated whenever there is a change in the state or the props) |
getDerivedStateFromProps() |
The
first method that is called when a component is updated. |
shouldComponentUpdate() shouldComponentUpdate() { return false; } |
Returns
a Boolean value to specify whether React should continue with the rendering
or not. Default value is true. |
|
render() |
Called
when a component gets updated. Re-render the HTML to the DOM. |
|
getSnapshotBeforeUpdate() getSnapshotBeforeUpdate(prevProps, prevState) { document.getElementById("div1").innerHTML = "Before the update,
the favorite was " + prevState.favoritecolor; } |
You
have the access to the props and state before the update. It means even after
the update, you can check what were the values before the update. |
|
componentDidUpdate() componentDidUpdate() { document.getElementById("mydiv").innerHTML = "The updated favorite
is " + this.state.favoritecolor; } |
Called
after the component is updated in the DOM. |
|
render() method is required and always be called
while other methods are optional will be called only when you define them. |
||
Unmounting (when
the component is removed from the DOM) |
componentWillUnmount() componentWillUnmount() { alert("The component named
Header is about to be unmounted."); } |
Called
when the component is about to be removed from the DOM |
Just like
HTML, react can perform actions based on the user events.
React has
the same events as HTML : click , change , mouseover etc.
React
events are written in camelCase and written inside curly braces.
In React:
<button onClick={shoot}>Take the Shot!</button>
In HTML the above line written as :
<button onclick="shoot()">Take the Shot!</button>
·
In
regular functions the this
keyword
represents the object that called the function. Which could be window,
document, button or whatever.
·
In
arrow function the this
keyword
represents the object that defined the arrow function.
Advantages of React
·
Easy
to learn and use (Any one who comes from the javascript background can
easily develop apps using react within few days)
·
Easy
to create dynamic web applications (It has less coding but more
functionality. Uses JSX(extension of javascript) where renders HTML quates and
tags)
·
Performance
Enhancement (It is because of the virtual DOM. It takes more time when
updating the DOM. But instead of that React will update the virtual DOM first
and then it will send only the particular changes the DOM. Developer will not
be updating the DOM directly. )
·
Very
useful to create attractive user interfaces.
·
SEO
(Search Engine Optimization) friendly (Most of the search engines are
unable to read javascript-heavy applications. But reactjs makes that process
easier by rendering the virtual DOM and returns to the browser as a regular web
page)
Disadvantages of React
·
JSX
as a barrier (JSX is an extension of javcascript where HTML and javascript
will be coded together as a mixture. Some developers says it is complex and
they find it as a barrier)
·
View
Part (ReactJS
develops only the UI layer of an app. So you need to find some other tools too
to develop the project)
·
Poor
Documentation (React updates so fast where it does not have time to make a
proper documentation for each update)
Comments
Post a Comment