*********************************************************
[Link]
*********************************************************
props
SPA
SPA with Nested routing
Imports and Exports
JSON Server
Asynchronous calls CRUD operations using AXIOS
Component Lifecycle Methods
*********************************************************
==================================================
Props:-
==================================================
- props are used to share data between components.
***[Link]***
import React from "react";
import Second from "./Second";
export default class First extends [Link]{
constructor(){
super()
[Link] = {
technology : 'Mern Stack',
number : 100,
flag : true,
obj : {
fruits : "Apple"
},
subs : [`Bootstrap`,`Express`,`React`]
render(){
return(
<div>
<h1 className="text-primary">Welcome to props </h1>
<Second data1 = {[Link]}></Second>
<Second data2 = {[Link]}></Second>
<Second data3 = {[Link]}></Second>
<Second data4 = {[Link]}></Second>
<Second data5 = {[Link]}></Second>
</div>
***[Link]***
import React from 'react'
export default class Second extends [Link]{
render(){
return(
<div>
<h1 className='text-primary'>{[Link].data1} </h1>
<h1 className="text-secondary">{[Link].data2}</h1>
<h1 className="text-success">{[Link]([Link].data3)} </h1>
<h1 className="text-warning">{[Link]([Link].data4)} </h1>
<h1 className="text-danger">{[Link].data5} </h1>
<h1 className="text-dark"></h1>
</div>
)
}
==================================================
Form Inputs
==================================================
import React from "react"
export default class FormInput extends [Link]{
constructor(){
super()
[Link] = {
status : 'Please Login'
render(){
return(
<div>
<form onSubmit = {[Link]}>
<input type = 'email'
placeholder = 'Enter email'
name = 'uemail'></input>
<br/><br/>
<input type = "password"
placeholder = 'Enter password'
name = 'upwd'></input>
<br/><br/>
<input type = 'submit' value = 'Login'></input>
</form>
<h1 style = {{color:'blue'}}>{[Link]} </h1>
</div>
)
login = (e) =>{
[Link]()
let uemail = [Link]
let upwd = [Link]
if(uemail === 'admin@[Link]' && upwd === 'admin')
[Link]({status : 'Login Success'})
else
[Link]({status : 'Login Failed'})
==============================================
Single Page Application
==============================================
- Loading one component to another component without refreshing
the whole webpage is called as single page application.
- Navigation of components in SPA is called as routing.
- 'BrowserRouter' is used to perform navigation.
- 'Route' is used to render particular component.
- All navigations are in 'Routes'
- 'NavLink' defines link to particular component.
- BrowserRouter, Route, Routes and NavLink
are available in 'react-router-dom' library.
- react-router-dom library can be downloaded by
>yarn add react-router-dom --save
<>
src
SPA
Components
[Link]
[Link]
[Link]
[Link]
[Link]
***[Link]***
import React from 'react'
export default class ReadComponent extends [Link]{
constructor(){
super()
[Link] = {
products : []
render(){
return(
<div className='container mt-2'>
<div className='text-warning h1'>I am from Read Component</div>
</div>
Similarly create
CreateComponent,
UpdateComponent,
DeleteComponent
***[Link]***
import React from 'react'
import {BrowserRouter as Router, NavLink, Route, Routes} from 'react-router-dom'
import CreateComponent from './CreateComponent'
import ReadComponent from './ReadComponent'
import UpdateComponent from './UpdateComponent'
import DeleteComponent from './DeleteComponent'
export default class IndexComponent extends [Link]{
render(){
return(
<div>
<div className='nav nav-pills'>
<Router>
<div className='nav-item'>
<NavLink to = "/create" className='nav-link'>Create</NavLink>
</div>
<div className="nav-item">
<NavLink to="/read" className='nav-link'>Read</NavLink>
</div>
<div className="nav-item">
<NavLink to="/update" className='nav-link'>Update</NavLink>
</div>
<div className="nav-item">
<NavLink to="/delete" className='nav-link'>Delete</NavLink>
</div>
<br/><br/>
<Routes>
<Route path = "/create" element = {<CreateComponent/>}></Route>
<Route path="/read" element={<ReadComponent />}></Route>
<Route path="/update" element={<UpdateComponent />}></Route>
<Route path="/delete" element={<DeleteComponent />}></Route>
</Routes>
</Router>
</div>
</div>
***[Link]***
...
const root = [Link]([Link]('root'));
[Link](
<IndexComponent/>
);
...
***[Link]***
in head section -> Bootstrap CDN
<link rel="stylesheet"
href="[Link]
<link rel="stylesheet" href="[Link]
[Link]">
<script src="[Link]
<script src="[Link]
<script src="[Link]
==============================================
Nested Routing
==============================================
***[Link]***
import React from 'react'
export default class CreateSingleComponent extends [Link] {
constructor() {
super()
[Link] = {
status : ''
render() {
return (
<div className='container mt-2'>
<div className='h3 text-warning'>I am from Create Single Component</div>
</div>
now do changes in
***[Link]***
...
render() {
return (
<div className='container mt-2'>
<div className='h1 text-warning'>I am from Create Component</div>
<NavLink to = "createSingle">Create Single</NavLink>
</div>
)
...
***[Link]***
<Routes>
<Route path = "/create" element = {<CreateComponent/>}></Route>
<Route path="/read" element={<ReadComponent />}></Route>
<Route path="/update" element={<UpdateComponent />}></Route>
<Route path="/delete" element={<DeleteComponent />}></Route>
<Route path='/create/createSingle' element={<CreateSingleComponent/>}></Route>
</Routes>
==============================================
Imports and exports in ReactJS
==============================================
- As react developer we can export variables,
objects, functions, etc
- As react developer we import any exported
variables, objects, functions, etc
Note:-
1. While exporting there must be ONE member as default.
2. While exporting
export {member1, member2, member3,...}
where member1 is default.
3. If we write default keyword, then it can be imported with any name.
Directory structure
<>
src
ios
- [Link]
- [Link]
- [Link]
***[Link]***
let url = `[Link]
let flag = "true"
let score = 88
let db_config = {
host: "localhost",
user: "root",
password: "root",
database: "nodedb",
table: "products"
export default url
export { flag, score, db_config }
***[Link]***
function fun_one(){
return `Welcome to my function`
function auth(arg1, arg2){
if(arg1 === 'admin' && arg2 === 'admin')
return true
else
return false
export default fun_one
export {auth}
***[Link]***
import React from 'react'
//import url, { db_config, flag, score } from './variables'
import * as obj from './variables'
import fun_one, { auth } from './functions'
export default class MyComponent extends [Link] {
render() {
return (
<div>
{/*<p style={{ color: 'rgb(255,0,0)' }}>Url:- {url} </p>
<p style={{ color: 'rgb(200,0,0)' }}>Flag:- {flag} </p>
<p style={{color:'rgb(180,0,0)'}}>Score :- {score}</p>
<p style={{color:'rgb(160,0,0)'}}>Database Configuration :-
{[Link](db_config)}</p>*/}
<p style={{ color: 'rgb(255,0,0)' }}>Url:- {[Link]} </p>
<p style={{ color: 'rgb(200,0,0)' }}>Flag:- {[Link]} </p>
<p style={{ color: 'rgb(180,0,0)' }}>Score :- {[Link]}</p>
<p style={{ color: 'rgb(160,0,0)' }}>Database Configuration :-
{[Link](obj.db_config)}</p>
<p style={{ color: 'rgb(0,0,255)' }}>{fun_one()} </p>
<form onSubmit={[Link]}>
<input type='text' placeholder='Enter Username' name='uname'></input>
<br/><br/>
<input type='password' placeholder='Enter Password' name='upwd'></input>
<br/><br/>
<input type = 'submit' value='Login'></input>
</form>
</div>
login = (e) =>{
let uname = [Link]
let upwd = [Link]
let login = auth(uname, upwd)
if(login)
alert('Authentication success')
else
alert('Authentication failed')
============================================
JSON Server
============================================
- JSON Server is used to create demo ReST JSON services.
(ReST:- Representational State Transfer)
- JSON server can be used to develop
GET
PUT
POST
DELETE, ... etc services.
- JSON server supports only JSON.
- JSON server is light weight server.
- JSON server installed using folllowing command
>npm install -g json-server@latest
$sudo npm install -g json-server@latest
Deployig JSON server
1. Create JSON file
[Link]
"products" : [
{ "id":1, "p_id":111, "p_name":"P_one", "p_cost":10000 },
{ "id":2, "p_id":222, "p_name":"P_two", "p_cost":20000 },
{ "id":3, "p_id":333, "p_name":"P_three", "p_cost":30000 },
{ "id":4, "p_id":444, "p_name":"P_four", "p_cost":40000 },
{ "id":5, "p_id":555, "p_name":"P_five", "p_cost":50000 }
Note:- while creating JSON unique id is compulsary, duplicate ids will be discarded
2. deploy [Link] in JSON server
>json-server --watch [Link]
OR
>json-server -w [Link]
by default JSON server running on port no 3000
3. Changing port no (optional)
>json-server -w [Link] -p 3001
test it with postman ([Link]
GET
[Link] -> all records
[Link] -> specific record
[Link] -> specific records based on data
POST
[Link]
body -> raw -> text <-> json Refer fig
"id" : 6,
"p_id" : 666,
"p_name" : "P_six",
"p_cost" : 60000
PUT
[Link]
body -> raw -> json
"id" : 5,
"p_id" : 555,
"p_name" : "P_FIVE_UPDATED",
"p_cost" : 55555
on scucess status -> 200 OK
on failure status -> 404 Not found
DELETE
[Link]
on scucess status -> 200 OK
on failure status -> 404 Not found
==========================================================
Asynchronous calls CRUD Operations
==========================================================
- axios library is used to make asynchronous calls
- download axios library using following command
>yarn add axios --save
***[Link]***
import axios from 'axios'
import React from 'react'
export default class ReadComponent extends [Link] {
constructor() {
super()
[Link] = {
products: [],
status:""
componentDidMount(){
[Link]("[Link]
[Link]({
status : 'Loading'
})
[Link]({
products : [Link],
status : ''
})
},(errRes)=>{
[Link](errRes)
})
render() {
return (
<div className='container mt-2'>
<div className='h1 text-success'>I am from Read Component</div>
<h1 className='text-danger'>{[Link]} </h1>
<table className='table table-bordered table-dark table-striped table-hover w-50 mx-
auto'>
<thead>
<tr>
<th>Sr No</th>
<th>ID</th>
<th>P_id</th>
<th>P_name</th>
<th>P_cost</th>
</tr>
</thead>
<tbody>
{[Link]((element, index)=>(
<tr>
<td>{index+1} </td>
<td>{[Link]}</td>
<td>{element.p_id}</td>
<td>{element.p_name}</td>
<td>{element.p_cost}</td>
</tr>
))}
</tbody>
</table>
</div>
***[Link]***
import axios from 'axios'
import React from 'react'
import { NavLink } from 'react-router-dom'
export default class CreateComponent extends [Link] {
constructor() {
super()
[Link] = {
status: ''
render() {
return (
<div className='container mt-2'>
<div className='h1 text-warning'>I am from Create Component</div>
<div>
<form onSubmit={[Link]}>
<input type="number"
placeholder="P_id"
name="p_id"
className="form-control my-2"></input>
<input type="text"
placeholder="P_name"
name="p_name"
className="form-control my-2"></input>
<input type="number"
placeholder="P_cost"
name="p_cost"
className="form-control my-2"></input>
<input type='submit' value="Create" className="btn btn-success"></input>
</form>
<h1 className='text-primary'>{[Link]} </h1>
</div>
</div>
insert = (e) =>{
[Link]()
[Link]({
status : 'Loading'
})
let obj = {
"p_id" : parseInt([Link].p_id.value),
"p_name" : [Link].p_name.value,
"p_cost" : parseInt([Link].p_cost.value)
[Link]("[Link]
.then((posRes)=>{
[Link]({
status : 'Record' + [Link]
})
},(errRes)=>{
[Link](errRes)
})
}
}
***[Link]***
import axios from 'axios'
import React from 'react'
export default class UpdateComponent extends [Link] {
constructor() {
super()
[Link] = {
status: ''
render() {
return (
<div className='container mt-2'>
<div className='h1 text-primary'>I am from Update Component</div>
<div>
<form onSubmit={[Link]}>
<input type="number"
placeholder="id"
name="id"
className="form-control my-2"></input>
<input type="number"
placeholder="P_id"
name="p_id"
className="form-control my-2"></input>
<input type="text"
placeholder="P_name"
name="p_name"
className="form-control my-2"></input>
<input type="number"
placeholder="P_cost"
name="p_cost"
className="form-control my-2"></input>
<input type='submit' value="Update" className="btn btn-success"></input>
</form>
<h1 className='text-primary'>{[Link]} </h1>
</div>
</div>
update = (e) => {
[Link]()
[Link]({
status: 'Loading'
})
let id = parseInt([Link])
let obj = {
"p_id": parseInt([Link].p_id.value),
"p_name": [Link].p_name.value,
"p_cost": parseInt([Link].p_cost.value)
[Link]("[Link] + id, obj)
.then((posRes) => {
[Link](posRes)
[Link]({
status: 'Update ' + [Link]
})
}, (errRes) => {
[Link](errRes)
[Link]({
status: [Link]
})
})
***[Link]***
import axios from 'axios'
import React from 'react'
export default class DeleteComponent extends [Link] {
constructor() {
super()
[Link] = {
status: ''
render() {
return (
<div className='container mt-2'>
<div className='h1 text-danger'>I am from Delete Component</div>
<form onSubmit={[Link]}>
<input type="number"
placeholder="id"
name="id"
className="form-control my-2"></input>
<input type='submit' value="Delete" className="btn btn-success"></input>
</form>
<h1 className='text-primary'>{[Link]} </h1>
</div>
}
delete = (e) => {
[Link]()
[Link]()
[Link]({
status: 'Loading'
})
let id = parseInt([Link])
[Link]("[Link] + id)
.then((posRes) => {
[Link](posRes)
[Link]({
status: 'Delete ' + [Link]
})
}, (errRes) => {
[Link](errRes)
[Link]({
status: [Link]
})
})
==================================================
Lifecycle Methods
==================================================
import React from 'react'
import Child from './Child'
export default class Parent extends [Link] {
constructor() {
super() //super class constructor
[Link]("Parent constructor called")
/*
- constructor gets called at loading of component
- constructor will execute only once.
- it is recommanded to define state in constructor.
*/
[Link] = {
technology: 'ReactJS'
componentWillMount() {
[Link]("Parent componentWillMount called")
/*
- This method executes after constructor
- This method executes only once.
- It is recommanded to change initial state in this method.
- It is recommanded to set global parameters here
*/
if ([Link] < 600)
[Link]({
width: 'Small Page'
})
render() {
[Link]('Parent render called')
/*
- render is mandatory lifecycle method
- it will execute after componentWillMount method.
- we place presentation logic here
- it will always gets called when state change
*/
return (
<div>
<h1>Parent Component</h1>
<p style={{ color: 'blue' }}>{[Link]}</p>
<p style={{ color: 'red' }}>{[Link]} </p>
<Child key1={[Link]}></Child>
<button onClick={() => [Link]({ technology: 'MERN' })}>Change</button>
</div>
/*
--- Execution Flow ---
- Parent Constructor
- Parent componentWillMount
- Parent render
- Child Constructor
- Child componentWillMount
- Child render
- if state / props change detected
- Parent render
- Child reder
*/
componentDidMount() {
/*
- this method will execute after render method.
- priority goes to child componentDidMount()
- in general we will make ReST API call here
- we can change state here also
*/
[Link]('Parent componentDidMount')
}
/*
--- Execution Flow ---
- Parent Constructor
- Parent componentWillMount
- Parent render
- Child Constructor
- Child componentWillMount
- Child render
- if state / props change detected
- Parent render
- Child reder
- Child componentDidMount
- Parent componentDidMount
*/
componentWillReceiveProps() {
/*
- this method will execute if component receives props
*/
[Link]("Parent componentWillReceiveProps called")
shouldComponentUpdate() //control state change
/*
- this method controls the state change
- return true -> change the state
- return false -> dont change the state
*/
[Link]("Parent shouldComponentUpdate")
return true
componentDidUpdate() {
[Link]("Parent componentDidUpdate")
/*
- Before unmounting the components react library will execute the following methods
- these methods are used to perform cleanup operations
- eg nullifying instances, empty states, empty props, cancel subscriptions, etc
*/
componentWillUnmount() {
[Link]("Parent componentWillUnmount")
import React from 'react'
export default class Child extends [Link] {
constructor() {
super() //super class constructor
[Link]("Child constructor called")
componentWillMount() {
[Link]("Child componentWillMount called")
render() {
[Link]('Child render called')
return (
<div>
<h1>Child Component</h1>
<h4>{[Link].key1}</h4>
</div>
}
componentDidMount() {
[Link]("Child componentDidMount called")
componentWillReceiveProps() {
[Link]("Child componentWillReceiveProps called")
shouldComponentUpdate() {
[Link]("Child shouldComponentUpdate")
return true
componentDidUpdate() {
[Link]("Child componentDidUpdate")
componentWillUnmount() {
[Link]("Child componentWillUnmount")