React JS
Front-end library used for developing code to create GUI for web
application
Created by Jordan Walke, a software engineer at Facebook
Open sourced to the world by Facebook and Instagram.
It is widely used for building user interfaces for web
applications where user interactions are dynamic and frequent.
React allows developers to create reusable UI components,
making the development process more modular and efficient.
Why React JS?
Creating web apps that handles huge amount of data
Creating Single page web Application
Creating reusable GUI component
Code to be written for manipulating DOM tree after user clicking the like
button and re-render the web page in a browser
Above activity should be reflected in other users too.
Considering the application size of Facebook which has more than 1.6
billion daily users and 500,000 “likes” every minutes, this was a
challenge to the engineers of Facebook.
Single Page Application
A single-page application is an app that works inside a browser and
does not require page reloading during use.
You are using this type of applications every day. These are, for
instance: Gmail, Google Maps, Facebook or GitHub.
Key Features
Component-based: Components are the smallest unit in a React
application. Anything that we want to render is rendered through
components. Components help in maintainability and reusability.
Virtual DOM: React uses virtual DOM concept for DOM manipulation
which improves the performance of the application.
The virtual DOM is a lightweight copy of the actual DOM, allowing React
to calculate the most efficient way to update the real DOM, resulting in
improved performance.
Unidirect
ional
data
flow: Rea
ct’s one-
way data
flow (also
called one
-way
binding)
keeps
everything modular and fast and easy for debugging.
JSX syntax: React used JSX syntax which is similar to XML and HTML
syntax which makes it easy for writing markup and binding events in
components
- JSX stands for JavaScript XML. JSX allows us to write HTML in
React.
- JSX makes it easier to write and add HTML in React
Difference Between Angular JS and React JS
React Angular
React is a small view library Angular is a full framework
React covers only the rendering Angular provides the complete solution
and event handling part for front-end development
Presentation code in JavaScript Presentation code in HTML embedded with
powered by JSX JavaScript expressions
React's core size is smaller than Angular being a framework contains a lot of
Angular, so bit fast code, resulting in longer load time
React is very flexible Angular has less flexibility
Great performer, since it uses Angular uses actual DOM which affects its
Virtual DOM performance
React JS Installation
Need create-react-app tool. This is available as part of Node js
Install Node Js using the following link
https://nodejs.org/en/download/
After installation, go to the terminal of visual code and type the
following command
node –v
npx create-react-app@latest my-app
The above command creates a project my-app with the below folder
structure:
The description of folder structure is
Files Purpose
All the node module dependencies are created in this
node_modules
folder (babel)
This folder contains the public static assets of the
public
application
public/ First page that is rendered on the browser or [age
index.html template
src All application related files/folders are created in this folder
src/index.js Entry point of the application
package.json Contains the dependencies of the React application
D:/>my-app>npm start
After successful compilation, application will be loaded in the browser at the
port "http://localhost:3000" as shown below
Why Components?
We have the following challenges in developing this application:
1. Entire page will get re-rendered even when a section of the page (eg. feedback
section) undergoes changes
2. We will have to re-write code for each item even though they have similar
behavior
3. We will have to take additional care to make sure that the functionality of one
part of the application do not interfere with another part
If we implement the above wireframe by dividing them into components - encapsulating
its own data and presentation logic then we can achieve modularity and re-usability.
What is React Component?
Whenever any updates happen in the application, the virtual DOM gets
modified. React computes the difference between the previous virtual
tree and the current virtual tree
Based on these differences React will figure out how to make updates to
the actual DOM efficiently
React does all the computations in its abstracted DOM and updates the
DOM tree accordingly
Virtual DOM enhances performance and efficiency by minimizing
expensive updates in the actual DOM
Creating a Component
App.js
import React from 'react';
class App extends React.Component {
render() {
return React.createElement("h1", { }, "Hello World!!!");
}
}
export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App/>, document.getElementById('root'));
Why JSX?
Let us understand the need of JSX by taking the below example:
function App() {
return React.createElement(
'form', {},
React.createElement('h1', {}, 'Login'),
React.createElement('input', { type: 'text', placeholder: 'Name',
value: '' }),
React.createElement('br', {}),
React.createElement('br', {}),
React.createElement('input', { type: 'password', placeholder:
'Password', value: '' }),
React.createElement('br', {}),
React.createElement('br', {}),
React.createElement('button', { type: 'submit' }, 'Login')
);
}
export default App;
Let us see how to write the same above Login component using JSX
in a easier way:
class App extends React.Component{
render(){
return (
<form><h2>Login</h2>
<input type="text" placeholder="Name" /><br/><br/>
<input type="password" placeholder="password" /> <br/><br/>
<input type="submit" value="log" />
</form>
);
}};
export default App;
JSX is a special syntax introduced in ReactJS to write elements of
components. It is syntactically identical to HTML and hence it can be easily
read and written. Code written using JSX helps in visualizing the DOM
structure easily.
class App extends React.Component {
render() {
return <h1> Hello World </h1>
}
}
export default App;
As the browser does not understand JSX code, this gets converted to JavaScript using
the plugins of the babel.
Conversion of JSX to JavaScript happens as shown below:
<React.Fragment>
React Fragments allow you to wrap or group multiple elements without adding an
extra node to the DOM. This can be useful when rendering multiple child
elements/components in a single parent component.
React.Fragment is almost always the better choice to reduce the overall DOM size.
class App extends React.Component {
render(){
return
<React.Fragment>
<h3>ReactJS:</h3>
<img src="./image/react.PNG" width="120" height="120"/>
<p> React is a JavaScript library for creating User
Interfaces.</p>
</React.Fragment>
}
}
Javascript Expression in JSX
We discussed how to use JSX to create React elements, we may also require
to use JavaScript expressions in React elements, so let's see how to write
JavaScript expressions in JSX.
{}
JavaScript expressions to be evaluated should be wrapped within curly braces
as follows:
<h1> { Expression to be evaluated } </h1>
Accessing a variable:
We can access the value of any variable within curly braces as shown below:
class App extends React.Component {
render() {
let count = 5
return(<React.Fragment>
<h1>{count}</h1>
<h2>{count*count}</h2>
</React.Fragment>)
}}
Arithmetic operators can also be used as shown above
Accessing an object:
The properties of an object can be accessed as shown below:
class App extends React.Component {
render() {
let name = {
firstName: 'Iraivi',
lastName: 'Naveenkumar'
}
return(<React.Fragment>
<h1>{name.firstName} {name.lastName}</h1>
</React.Fragment>)
}
}
Specifying attributes' expression:
We can provide dynamic values to attributes as shown below:
class App extends React.Component {
render() {
let highlight = {
color: 'green',backgroundColor:'grey'
}
return(<React.Fragment>
<h1 style={highlight}>Welcome to React</h1>
</React.Fragment>)
}
}
export default App;
Create a component to display an algebraic expression as follows:
import React from 'react';
class App extends React.Component {
render() {
var x=25, y=30
return (<div>
<h2> Evaluating expression </h2>
<h3> {x} {">"}{y} {":"} {x>y ? 'True' : 'False'} </h3>
</div>)
}
}
export default App;
Conditional Rendering
class App extends React.Component {
render() {
let element = null;
let isLoggedIn = false
if(isLoggedIn) {
element = <h2>Welcome Admin</h2>
}
else {
element = <h2>Please Login</h2>
}
return (<React.Fragment>
{element}
</React.Fragment>)
}
}
export default App;
Using a Ternary operator
class App extends React.Component {
render() {
var employees = [
{ empId: 1234, name: 'John', designation:'SE' },
{ empId: 4567, name: 'Tom', designation:'SSE'},
{ empId: 8910, name: 'Kevin',designation:'TA'}
]
return (<React.Fragment>
<table style={{width:'60%'}} className='table'>
<thead className="thead-light">
<tr>
<th>EmpID</th>
<th>Name</th>
<th>Designation</th>
</tr>
</thead>
<tbody>
{employees.map(employee => {
return (<tr>
<td>{employee.empId}</td>
<td>{employee.name}</td>
<td>{employee.designation}</td>
</tr>)
})
}
</tbody>
</table>
</React.Fragment>)
}}
export default App;
Error
<tbody>
{ employees.map(employee => {
return (<tr key={employee.empId}>
<td>{employee.empId}</td>
<td>{employee.name}</td>
<td>{employee.designation}</td>
</tr>)
})
}
</tbody>
Another Example
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
class App extends React.Component {
render() {
var employees = [
{ empId: 1234, name: 'Jack', designation:'SE', salary:23000},
{ empId: 4567, name: 'Johnson', designation:'SSE',
salary:15000},
{ empId: 8910, name: 'Sachin',designation:'TA', salary:30000}
]
return (<React.Fragment>
<table style={{width:'60%'}} className='table'>
<thead className="thead-light">
<tr>
<th>EmpID</th>
<th>Name</th>
<th>Designation</th>
</tr>
</thead>
<tbody>
{employees.map(employee => {
return employee.salary > 15000 ? (<tr
key={employee.empId}>
<td>{employee.empId}</td>
<td>{employee.name}</td>
<td>{employee.designation}</td>
</tr>) : null
})
}
</tbody>
</table>
</React.Fragment>)
}
}
export default App;
Styling the Component
Inline Style Components
In React, components will have inline styles and it should be specified as an
object as shown below
<h1 style={{color:'green'}}>Welcome to React</h1>
When we have CSS properties with multiple words like background-color,
font--family etc, in React, those properties should be camelCased by
removing hypen as shown below.
<h1 style={{color:'green',fontFamily:'verdana'}}>Welcome to
React</h1>
External Style Components
1. Go to the public folder in React Project Folder
2. Edit the App.css
3. Define the CSS rules
.button {
background-color:blue;
color:white;
border-radius:10px;
width:100px;
height:30px;
}
4. Class attribute should be named as “className”
import './App.css';
<button className="button">Submit</button>
Style the component using Bootstrap
npm install bootstrap
import the bootstrap CSS file within the AppComp component and apply the
bootstrap btn btn-success class to the button as shown below
import 'bootstrap/dist/css/bootstrap.min.css';
<button className="btn btn-success">Submit</button>
If you are using the js file of Bootstrap then import the bootstrap js file but
before that install jQuery, as the bootstrap JavaScript depends on jQuery
What is State?
The state is an initial value set for a component, which is used for interactivity.
Let's see how to set the state of a component.
Using constructor, the state of a component is created and initialized using this.state as
follows:
Syntax:
constructor() {
super();
this.state = { counter: 1 };
}
In the above code, the state 'counter' is set to 1 and 'counter' would be accessed
as this.state.counter.
As the user-defined component extends React.Component, it becomes a child
component of it. Hence, whenever a child component has a constructor, it has to call the
parent class's constructor using the super() method. And super() method should be the
first statement within a constructor.
import React from 'react'
class Timer extends React.Component {
constructor() {
super ()
this.state = {
counter: 0
}
this.handleClick=this.handleClick.bind(this)
}
handleClick(e){
this.setState({counter:this.state.counter+1})
}
render() {
return(<React.Fragment>
<h2> Seconds Elapsed: {this.state.counter} </h2>
<button onClick = {this.handleClick}> Increment
Counter </button>
</React.Fragment>)
}
}
export default Timer;
Calling a setState is Asynchronous
class App extends React.Component {
constructor() {
super()
this.state = {
quantity: 0,
price:0
}
}
update = () => {
this.setState({quantity:5})
if(this.state.quantity == 5) {
this.setState({price:2000-100})
}
}
render() {
return(<React.Fragment>
<h1>{this.state.quantity}</h1>
<h1>{this.state.price}</h1>
<button onClick={this.update}>Update</button>
</React.Fragment>)}
To handle Asynchronous, a Call back function is introduced
update = () => {
this.setState({quantity:5},()=>{
if(this.state.quantity == 5) {
this.setState({price:2000-100})
}
})
}
Key points to be remembered while handling data in a component:
States are mutable and only used on top level component
They are reserved only for interactivity and component's event handlers may
change to trigger a UI update
The state will be set with a default value when component mounts and will mutate
in time based on user events generated
Props
When we want to pass any data from one component to another component, it is passed
as a prop.
Props allow us to pass data from one component to another component
Props are immutable - a component cannot change its props however it is
responsible for putting together
Props can be accessed as this.props
How to use props?
Let's now learn how to pass data to a component:
<App initial = {10} />
Here, we are passing a property 'initial' with a value '10', to a
component App.
In the component App, this property would be accessed as this.props.initial
Passing a values to Class Component
import React from 'react'
class Pass extends React.Component
{
render()
{
return(
<div>
<h1> Accessing Props</h1>
<h2> {this.props.name}</h2>
{
console.log(this.props.name)
}
</div>
export default Pass;
<Pass name="Sona College fo technology"/>
Passing Props to functional component
<Pass2 name="V.Mohanraj"/>
function Pass2(props)
{
return(
<h1> {props.name}</h1>
)
}
export default Pass2;
Parent component to child component
import React from 'react';
import ReactDOM from 'react-dom';
// Parent Component
class Parent extends React.Component{
render(){
return(
<div>
<h2>You are inside Parent Component</h2>
<Child name="User" userId = "5555"/>
</div>
);
}
}
// Child Component
class Child extends React.Component{
render(){
console.log(this.props);
return(
<div>
<h2>Hello, {this.props.name}</h2>
<h3>You are inside Child Component</h3>
<h3>Your user id is: {this.props.userId}</h3>
</div>
);
}
}
ReactDOM.render(
// passing props
<Parent />,
document.getElementById("root")
);
import React from 'react';
class Incdec extends React.Component
{
constructor()
{
super();
this.state={counter:0};
this.Incr=this.Incr.bind(this);
this.Decr=this.Decr.bind(this);
}
Incr(e) {
console.log("Inside incr ")
this.setState({counter:this.state.counter+1})
Decr(e){
console.log("Inside decr ")
this.setState({counter:this.state.counter-1})
}
render()
{
return(
<div className='container-fluid'>
<h1 className='text-primary'> Counter Value:
{this.state.counter}</h1>
<input type="button" className="btn btn-success"
value="Increment" onClick={this.Incr}/>
<input type="button" className="btn btn-danger"
value="Decrement" onClick={this.Decr}/>
</div>
)
}
export default Incdec;
import React from 'react';
class Incdec extends React.Component
{
constructor()
{
super();
this.state={counter:0,mobile:9786123706};
this.Incr=this.Incr.bind(this);
this.Decr=this.Decr.bind(this);
this.setMobile=this.setMobile.bind(this);
}
Incr(e) {
console.log("Inside incr ")
this.setState({counter:this.state.counter+1})
Decr(e){
console.log("Inside decr ")
this.setState({counter:this.state.counter-1})
}
setMobile(e)
{
let m=this.props.mobile;
this.setState({mobile:m},()=>{
console.log(this.state.mobile);
})
}
render()
{
return(
<div className='container-fluid'>
<h1 className='text-primary'> Counter Value:
{this.state.counter}</h1>
<input type="button" className="btn btn-success"
value="Increment" onClick={this.Incr}/>
<input type="button" className="btn btn-danger"
value="Decrement" onClick={this.Decr}/>
<input type="button" className="btn btn-info"
value="Set Mobilenumber" onClick={this.setMobile}/>
</div>
)
}
export default Incdec;
CDN for Bootstrap 5
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/boots
trap.min.css" rel="stylesheet">
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstr
ap.bundle.min.js"></script>
Commenting a react component
{/* <componentname/>*/}
Passing the data between components
import React from 'react'
import ChildComponent from './Childcomp';
class ParentComponent extends React.Component {
render(){
return(
<div>
<ChildComponent message="Data from first component"/>
</div>
);
}
}
export default ParentComponent;
import React from 'react';
const ChildComponent = (props) => {
return(
<h2> {props.message} </h2>
);
}
export default ChildComponent;