React Js
React Js
React Js
Syllabus:
➢ Components
➢ Multiple Components
➢ State&Props
➢ Events&refs
➢ Pure Components
➢ Life cycle Hooks
➢ Unit Test Cases
➢ Introducton to Redux
➢ Multiple Reducers
➢ Integration of react and redux
➢ Saga Middleware
➢ Thunk Middleware
➢ Single Page Applications
➢ Lazy Loading
➢ Routing Parameters in SPA
➢ Crud Operations(MYSQL)
➢ Mini Project(MYSQL-MSSQL-MONGODB)
➢ Crud Operations(Thunk-Middleware)
➢ Mini project(Saga-Middleware)
➢ Server Files(MYSQL-MSSQL-MONGODB)
React Js
Commands
Create-react-app <application-name>
➢ Switch to project
Cd <project-name>
yarn start
Introduction
website : https://nodejs.org/en/
file : node-v14.4.0-x64.msi
React Js
Ex. Demo
> cd first-app
Directory Structure
node_modules
public/index.html
public/favicon.ico
o /logo192.png
o /logo512.png
React Js
public/manifest.json
public/robots.txt
src
src/App.js
App.css
App.test.js
src/index.js
src/serviceWorker.js
src/setupTests.js
package.json
Ex.
redux
redux-thunk
redux-saga
axios
yarn.lock
Chapter-1(Components)
➢ Simple "JSX Class" behaves like Component.
➢ React Applications are Component Based Applications.
➢ we can create more than one Component.
➢ These Components are Reusable.
➢ Because of Components, React Simplifies the Complex UI.
Stateful Components
> cd first-app
<script
src="https://unpkg.com/react/umd/react.production.min.js"
crossorigin></script>
<script src="https://unpkg.com/react-dom/umd/react-
dom.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-bootstrap@next/dist/react-
bootstrap.min.js" crossorigin></script>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootst
rap.min.css"integrity="sha384-
9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk
"crossorigin="anonymous"/>
Directory Structure
********************************************************
first-app
src
First.js
index.js
*******************************************************
React Js
First.js
render(){
return(
<div>
<Container fluid>
{/*
{['primary','info','danger','success','dark'].map((element,index
)=>(
React Js
<Alert variant={element}>Alert</Alert>
))} */}
<Alert variant={'danger'}>
<Alert.Heading>Heading</Alert.Heading>
<Button>Learn More</Button>
</Alert> </Container>
</div>
) }};
Index.js
import './index.css';
ReactDOM.render(
<First />,
document.getElementById('root'));
React Js
serviceWorker.unregister();
******************************************
Stateless Components
> cd first-app
Directory Structure
********************************************************
first-app
src
App.js
User.js
index.js
*******************************************************
React Js
App.js
render(){
return(
<div>
</div>
};
};
User.js
};
Index.js
import './index.css';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can
change
Chapter-2(Multiple-Components)
> cd demo-app
"https://material-ui.com/"
index.html
<link rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500
,700&display=swap" />
React Js
<link rel="stylesheet"
href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>
<script src="https://unpkg.com/@material-
ui/core@latest/umd/material-ui.development.js"></script>
<script src="https://unpkg.com/@material-
ui/core@latest/umd/material-ui.production.min.js"></script>
************************************************
demo-app
src
FrontEnd.js
Server.js
BackEnd.js
MernComponent.js
index.js
*************************************************
FrontEnd.js
render(){
return(
<div>
</div>
};
Server.js
render(){
return(
<div>
<Typography variant="h5">Deno</Typography>
</div>
} };
React Js
BackEnd.js
render(){
return(
<div>
<Typography variant="h5">Azure</Typography>
</div>
};
MernComponent.js
render(){
return(
<div>
React Js
<FrontEnd />
<Server />
<BackEnd />
</div>
};
index.js
import './index.css';
ReactDOM.render(
<MernComponent />,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can
change
React Js
serviceWorker.unregister();
***************************************
React Js
> cd data-app
Directory Structure
********************************************************
data-app
src
Parent.js
Child.js
Subchild.js
index.js
*******************************************************
React Js
Parent.js
constructor(){
super();
this.state = {
render(){
return(
<div>
<Child key1={this.state.data}/>
</div>
};
Child.js
constructor(){
super();
this.state = {
render(){
return(
<div>
<Subchild {...this.props}
key2={this.state.data}/>
</div>
};
Subchild.js
render(){
return(
<div>
React Js
<h1>{this.props.key1}......{this.props.key2}</h1>
</div>
}}
index.js
import './index.css';
ReactDOM.render(
<Parent />,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can
change
serviceWorker.unregister();
***********************************
React Js
> cd get-ex
Directory Structure
************************************************
Get-ex
src
Countries.js
index.js
*************************************************
React Js
Countries.js
constructor(){
super();
this.state = {
arr : []
};
componentDidMount(){
axios.get("https://restcountries.eu/rest/v2/all")
.then((posRes)=>{
this.setState({
arr : posRes.data
})
},(errRes)=>{
console.log(errRes);
});
};
React Js
render(){
return(
<div>
<table border="1"
cellPadding="10px"
cellSpacing="10px"
align="center">
<thead style={{backgroundColor:"grey"}}>
<tr>
<th>SNO</th>
<th>Name</th>
<th>Capital</th>
<th>NativeName</th>
<th>Population</th>
<th>Flag</th>
</tr>
</thead>
<tbody>
{this.state.arr.map((element,index)=>(
<tr key={index}>
<td>{index+1}</td>
<td>{element.name}</td>
React Js
<td>{element.capital}</td>
<td>{element.nativeName}</td>
<td>{element.population}</td>
<td><img width="100px"
height="50px" src={element.flag}></img></td>
</tr>
))}
</tbody>
</table>
</div>
};
index.js
import './index.css';
ReactDOM.render(
React Js
<Countries />,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can
change
serviceWorker.unregister();
React Js
Chapter-3(State&Props)
> cd first-app
Directory Structure
********************************************************
first-app
src
App.js
index.js
*******************************************************
App.js
}
}
render(){
return(
<div>
<table border="1"
cellPadding="10px"
cellSpacing="10px"
align="center">
<thead style={{backgroundColor:"grey"}}>
<tr>
<th>SNO</th>
<th>PID</th>
<th>PNAME</th>
<th>PCOST</th>
React Js
</tr>
</thead>
<tbody>
{this.state.products.map((element,index)=>
(
<tr>
<td>{index+1}</td>
<td>{element.p_id}</td>
<td>{element.p_name}</td>
<td>{element.p_cost}</td>
</tr>
))}
</tbody>
</table>
<h1>{JSON.stringify(this.state.boolean)}</h1>
<h1>{this.state.error}</h1>
<h1>{this.state.data}</h1>
</div>
)
}
}
index.js
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can
change
serviceWorker.unregister();
****************************************
setState()
> cd first-app
React Js
Directory Structure
********************************************************
first-app
src
App.js
index.js
*******************************************************
App.js
};
myFun = ()=>{
this.setState({
sub : "Angular10"
});
};
};
index.js
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can
change
serviceWorker.unregister();
********************************************
Props:
> cd first-app
Directory Structure
React Js
********************************************************
first-app
src
First.js
second.js
index.js
*******************************************************
First.js-:
Code:
constructor(){
super();
this.state = {
"data" : "React",
"version" : 16.8,
React Js
"flag" : true,
"obj" : {"cost":100000},
"arr" : [{"eno":111,"ename":"e_one","esal":10000},
{"eno":222,"ename":"e_two","esal":20000},
{"eno":333,"ename":"e_three","esal":30000},
{"eno":444,"ename":"e_four","esal":40000},
{"eno":555,"ename":"e_five","esal":50000}]
};
render(){
return(
<div>
<Second key1={this.state.data}
key2={this.state.version}
key3={this.state.flag}
key4={this.state.obj}
key5={this.state.arr}/>
</div>
};
};
React Js
Second.js-:
Code:
render(){
return(
<div>
<table border="1"
cellPadding="10px"
cellSpacing="10px"
align="center">
<thead style={{backgroundColor:"grey"}}>
<tr>
<th>SNO</th>
<th>ENO</th>
<th>ENAME</th>
<th>ESAL</th>
</tr>
React Js
</thead>
<tbody>
{this.props.key5.map((element,index)=>(
<tr>
<td>{index+1}</td>
<td>{element.eno}</td>
<td>{element.ename}</td>
<td>{element.esal}</td>
</tr>
))}
</tbody>
</table>
<h1>{JSON.stringify(this.props.key4)}</h1>
<h1>{JSON.stringify(this.props.key3)}</h1>
<h1>{this.props.key2}</h1>
<h1>{this.props.key1}</h1>
</div>
};
Index.js-:
React Js
import './index.css';
ReactDOM.render(
<React.StrictMode>
<First />
</React.StrictMode>,
document.getElementById('root')
);
serviceWorker.unregister();
React Js
OutPut:
state props
1. State is variables, but directly initialized 1. Props are owned by a parent
and managed by the component. component
2. A state is a variable which exists inside 2. props are read-only in the child
a component, that cannot be accessed component that receives from
and modified outside the component parent component. However, call
and can only be used inside the back functions can also be
component. Works very similarly to a passed, which can be executed
variable that is declared inside a inside the child to initiate an
function that cannot be accessed update.
outside the scope of the function in 3. props are immutable (unable to be
normal Javascript. changed).
3. The component itself will update the 4. Props” is a special keyword
state using the setState() function. in React, which stands for
4. States are declared inside the properties and is being used for
constructor via super() method. passing data from one component
to another.
React Js
Chapter-4(Events&Refs)
Events:
> cd events-app
Directory Structure
********************************************************
events-app
src
Event.js
index.js
*******************************************************
Event.js
// fun_one = ()=>{
// };
// render(){
// return(
// <div>
// <button
onClick={this.fun_one}>ClickMe</button>
// </div>
// )
// }
// };
// fun_one = (arg1,arg2)=>{
// alert("Login Success");
// }else{
// alert("Login Fail");
// }
// };
// render(){
React Js
// return(
// <div>
// </div>
// )
// };
// };
index.js
ReactDOM.render(
<Events />,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can
change
// unregister() to register() below. Note this comes with some
pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
React Js
**********************************************
Refs:
> cd events-app
Directory Structure
********************************************************
events-app
src
Event.js
index.js
*******************************************************
Event.js
constructor(){
super();
this.state = {
login : ""
};
};
render(){
return(
<div>
<fieldset>
<legend>Login Form</legend>
<input type="text"
ref="uname"
placeholder="User Name"></input>
<br></br><br></br>
<input type="password"
ref="upwd"
placeholder="User Password"></input>
React Js
<br></br><br></br>
<button onClick={this.login}>Login</button>
<br></br><br></br>
<h1>{this.state.login}</h1>
</fieldset>
</div>
login = ()=>{
this.setState({
login : "success"
})
}else{
this.setState({
login : "fail"
})
}
React Js
};
index.js
ReactDOM.render(
<Events />,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can
change
// unregister() to register() below. Note this comes with some
pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
*******************************************************
> cd events-app
Directory Structure
********************************************************
events-app
src
Event.js
index.js
*******************************************************
Event.js
constructor(){
super();
this.state = {
res : {}
};
render(){
return(
React Js
<div>
<input type="text"
ref="msg"
placeholder="Enter Message"></input>
<button onClick={this.fun_one}>Change</button>
<h1>{JSON.stringify(this.state.res)}</h1>
</div>
};
fun_one = ()=>{
axios.post("http://test-
routes.herokuapp.com/test/uppercase",{"message":this.refs.msg.va
lue})
.then((posRes)=>{
this.setState({
res : posRes.data
})
},(errRes)=>{
console.log(errRes);
});
};
React Js
index.js
ReactDOM.render(
<Events />,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can
change
// unregister() to register() below. Note this comes with some
pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
*******************************************
> cd demo-app
Directory Structure
********************************************************
demo-app
src
styles.css
index.js
*******************************************************
Compone.js
constructor(){
super();
this.state = {
data1 : "ReactJS",
data3 : "Deno",
React Js
data4 : "MongoDB"
};
};
render(){
return(
<div>
<Comptwo s_o={this.state.data1}
s_t={this.state.data2}
s_three={this.state.data3}
s_f={this.state.data4}/>
</div>
};
Comptwo.js
import "./styles.css"
return(
<div>
React Js
<h2 className="sub_one">{props.s_o}</h2>
<h2>{props.s_t}</h2>
<h2>{props.s_three}</h2>
<h2>{props.s_f}</h2>
</div>
};
styles.css
.sub_one{
color: white;
background : linear-gradient(180deg,red,black);
text-align: center;
padding: 10px;
margin: 10px;
border-radius: 20px;
index.js
import './index.css';
ReactDOM.render(
<compone />,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can
change
serviceWorker.unregister();
**********************************************
React Js
Chapter-5(Pure-components)
Just like Pure Functions in JavaScript, a React component is
considered a Pure Component if it renders the same output for the
same state and props value. React provides the Pure Component base
class for these class components. Class components that extend the
React.PureComponent class are treated as pure components.
3. this.forceUpdate() is called
Conclusion
Example:
> cd demo-app
Directory Structure
React Js
********************************************************
demo-app
src
Demo2.js (props)
Index.js
*******************************************************
Demo1.js
constructor(){
super();
this.state = {
num : 1
};
};
render(){
return(
React Js
<div>
<Demo2 key1={this.state.num}/>
</div>
);
};
componentDidMount(){
setInterval(()=>{
this.setState({
num : Math.random()
})
},1000);
};
};
Demo2.js
console.log("child render");
return(
<div>{props.key1}</div>
React Js
};
index.js
import './index.css';
ReactDOM.render(
<Demo1 />,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can
change
serviceWorker.unregister();
React Js
Chapter-6(Life-Cycle-Hooks)
• componentWillMount is executed before rendering, on both the
server and the client side.
Example:
> cd demo-app
Directory Structure
********************************************************
demo-app
src
app.js
React Js
child.js
Index.js
*******************************************************
App.js
}
};
render(){
//it will execute immidiately after componentWillMount
//in general we will place presentation logic (JSX)
//render() is the mandatory life cycle hook
//when ever change detected in state/props automatically
this life cycle hook will execute
console.log("parent render");
return(
<div>
{this.state.name}
<br></br>
{this.state.width}
<br></br><br></br>
<Child key1={this.state.name}></Child>
<br></br><br></br>
<button onClick={this.changeSub}>Change</button>
</div>
)
};
changeSub = ()=>{
this.setState({
name : "reactjs"
});
};
/*execution flow
parent constructor
parent componentWillMount
parent render
React Js
Child constructor
Child componentWillMount
Child render
componentDidMount(){
//after render function componentDidMount will execute
//first priority goes to child component componentDidMou
nt() life cycle hooks
//in general, we will make rest api calls Ex. get reque
st
//it's recomended to change state
console.log("parent componentDidMount");
};
/*
exuction flow
parent constructor
parent componentWillMount
parent render
Child constructor
Child componentWillMount
Child render
child componentDidMount
React Js
parent componentDidMount
*/
componentWillReceiveProps(){
//if component receives the props, then this life cycl
e hook will execute
console.log("parent componentWillReceiveProps");
};
/*
parent render
child componentWillReceiveProps
child render
*/
shouldComponentUpdate(){
//deciding life cycle hook on state change
//true -- change the state
//false - dont change state
console.log("parent shouldComponentUpdate");
return true;
};
//before unmounting the component react library will execute
following life cycle hooks
//these life cycle hooks used to perform the clean up operat
ions
//Ex. nullifu the instance members
//Ex. empty the state
//Ex. empty the Props ,..........
componentWillUpdate(){
console.log("parent componentWillUpdate");
React Js
}
componentDidUpdate(){
console.log("parent componentDidUpdate");
}
componentWillUnmount(){
console.log("parent componentWillUnmount");
}
};
Child.js
componentWillReceiveProps(){
console.log("child componentWillReceiveProps");
};
shouldComponentUpdate(){
console.log("Child shouldComponentUpdate");
return false;
};
componentWillUpdate(){
console.log("child componentWillUpdate");
}
componentDidUpdate(){
console.log("child componentDidUpdate");
}
componentWillUnmount(){
console.log("child componentWillUnmount");
}
};
index.js
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can
change
serviceWorker.unregister();
Output:
React Js
React Js
>create-react-app test-app
Directory Structure
******************************
Test-app
Src
App.test.js
******************************
App.test.js
expect(status).toBeInTheDocument();
});
expect(status).toBeInTheDocument();
});
>yarn test
React Js
Result:
React Js
Chapter-8(Introduction to Redux)
STATE MANAGEMENT:
elements exist.
WHAT IS REDUX:
TERMINOLOGY OF REDUX :
➢ Components in redux
Actions
Store
Reducers
Dispatch
Subscribe
State
getstate()
React Js
ACTIONS IN REDUX:
➢ Simply we call that actions are events.
➢ They are the only way we can send data from application
to Redux store. The data can be from user interactions,
API calls, or even form submissions.
➢ Actions are sent using the store.dispatch() method.
➢ Actions are plain JavaScript objects, and they must
have a type property to indicate the type of action to
be carried out.
➢ They must also have a payload that contains the
information that should be worked on the action.
STORE IN REDUX:
➢ The store holds the application state. There is only
one store in any Redux application.
➢ redux has one global store
➢ we can access the state stored, update the state, and
React Js
Syntax:
import { createStore } from 'redux';
REDUCERS IN REDUX:
➢ Reducers are a pure function in Redux, these Pure functions
are predictable.
➢ Reducers are the only way to change states in Redux.
➢ It is the only place where you can write logic and
calculations.
➢ reducers main job is to take “current state” and an ”
action “ and return the ”new state”
React Js
DISPATCH WORKING:
• we created store has a built-in function called dispatch
• then Call it with an action and Redux will call our
reducer with that action and then replace the state
with whatever your reducer returned.
SUBSCRIBE IN REACT:
• It helps to register a callback that Redux store will call
when an action has been dispatched.
• As soon as the Redux state has been updated, the
React Js
REDUX – INSTALLATION:
• Website: https://nodejs.org/
• You can check successful installation by opening the
command prompt and type “ node –v ”
• This will show you the latest version of Node in your system.
React Js
ReduxEx
2) switch to ReduxEx
> cd ReduxEx
Directory Structure
********************************************************
ReduxEx
Demo.js
*******************************************************
Demo.js
const initialState = {
bal : 5000
};
switch(actions.type){
case "DEPOSIT":
newState.bal+=actions.value;
break;
case "WITHDRAW":
newState.bal-=actions.value;
break;
return newState;
React Js
};
store.subscribe(()=>{
console.log(store.getState());
});
store.dispatch({type:"DEPOSIT",value:5000});
store.dispatch({type:"DEPOSIT",value:5000});
store.dispatch({type:"DEPOSIT",value:5000});
store.dispatch({type:"WITHDRAW",value:1000});
store.dispatch({type:"DEPOSIT",value:5000});
store.dispatch({type:"WITHDRAW",value:10000});
> cd redux-ex
=> redux
=> react-redux
*****************************************
redux-ex
src
reducer
reducer.js
*****************************************
*****************************************
redux-ex
src
reducer
reducer.js
App.js
React Js
Index.js
*****************************************
reducer.js
const initialState = {
products : []
};
switch(action.type){
case "PRODUCTS":
return{
...state,
products:[
{"p_id":111,"p_name":"p_one","p_cost":10000},
{"p_id":222,"p_name":"p_two","p_cost":20000},
{"p_id":333,"p_name":"p_three","p_cost":30000},
{"p_id":444,"p_name":"p_four","p_cost":40000},
{"p_id":555,"p_name":"p_five","p_cost":50000}]
return state;
};
App.js
render(){
return(
<div>
<button
onClick={this.props.getProducts}>Products</button>
<br></br>
<h6>{JSON.stringify(this.props.products)}</h6>
</div>
) };
};
//subscribe
return{
products : state.products
};
//dispatch
return{
};
Index.js
import './index.css';
//import reducer
//import Provider
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can
change
serviceWorker.unregister();
React Js
Chapter-10(Multiple Reducers)
1) create the react application
> cd multiple-reducers-app
=> redux
=> react-redux
*****************************************
multiple-reducers-app
src
reducer
reducerA.js
reducerB.js
*****************************************
*****************************************
multiple-reducers-app
src
reducer
reducerA.js
reducerB.js
app.js
index.js
*****************************************
reducerA.js
const initialState = {
num1 : 1
};
switch(action.type){
case "UPDATE_A":
return{
...state,
}
React Js
break;
return state;
};
reducerB.js
const initialState = {
num2 : 1
};
switch(action.type){
case "UPDATE_B":
return{
...state,
num2:state.num2 + action.value
break;
return state;
};
app.js
render(){
return(
<div>
Num1 : <span
style={{color:"red",marginRight:100}}>{this.props.num1}</span>
Num2 : <span
style={{color:"red"}}>{this.props.num2}</span>
<br></br><br></br><br></br>
</div>
};
return{
React Js
num1 : state.rA.num1,
num2 : state.rB.num2
};
return{
updateNum1 : (data)=>{
dispatch({type:"UPDATE_A",value:data}) },
updateNum2 : (data)=>{
dispatch({type:"UPDATE_B",value:data}) }
};
index.js
import './index.css';
rA : reducerA,
rB : reducerB
});
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can
change
serviceWorker.unregister();
React Js
Chapter-11(Saga Middleware)
> cd redux-saga-example
=> redux
=> react-redux
**************************************************
redux-saga-example
src
saga
saga.js
*********************************************************
React Js
saga.js
function* ageUpAsync() {
yield delay(4000);
yield put({ type: "AGE_UP_ASYNC", value: 1 });
}
function* ageDownAsync(){
yield delay(2000);
yield put({type:"AGE_DOWN_ASYNC",value:1});
};
**************************************************
redux-saga-example
src
store
reducer.js
*********************************************************
React Js
reducer.js
reducer.js
const initialState = {
age: 20
};
switch (action.type) {
case "AGE_UP_ASYNC":
newState.age += action.value;
break;
case "AGE_DOWN_ASYNC":
newState.age -= action.value;
break;
}
return newState;
};
**************************************************
redux-saga-example
src
React Js
app.js
index.js
*********************************************************
Index.js
import "./index.css";
sagaMiddleware.run(watchAgeUp);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
React Js
document.getElementById("root")
);
app.js
return {
onAgeUp: () => dispatch({ type: "AGE_UP", value: 1 }),
onAgeDown: () => dispatch({ type: "AGE_DOWN", value: 1 })
};
};
export default connect(
mapStateToProps,
mapDispachToProps
)(App);
OutPut:
React Js
Chapter-12(thunk Middleware)
1) create the react application
> cd redux-thunk-example
Directory Structure
**************************************************
redux-thunk-example
src
actions
actions.js
reducer
reducer.js
app.js
index.js
*********************************************************
React Js
**************************************************
redux-thunk-example
src
reducer
reducer.js
*********************************************************
reducer.js
const initialState = {
bal : 5000
};
switch(action.type){
case "WITHDRAW":
newState.bal-=action.value;
break;
case "DEPOSIT":
newState.bal+=action.value;
break;
React Js
return newState;
};
**************************************************
redux-thunk-example
src
actions
actions.js
*********************************************************
actions.js
return {type:"WITHDRAW",value:val};
};
return {type:"DEPOSIT",value:val};
};
return (dispatch)=>{
setTimeout(()=>{
dispatch(onDepositAsync(val));
},5000);
};
redux-thunk-example
src
index.js
*********************************************************
index.js
import './index.css';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can
change
serviceWorker.unregister();
**************************************************
redux-thunk-example
src
app.js
*********************************************************
App.js
import "./App.css";
render(){
return(
<div className="App">
<h1>Balanace:<span style={{color:"green"}}>{this.pro
ps.bal}</span></h1>
<button onClick={this.props.withdraw}><b>Withdraw</b
></button>
<button onClick={this.props.deposit}><b>Deposit</b><
/button>
</div>
)
React Js
return{
bal : state.bal
};
return{
};
OutPut:
React Js
React Js
For example :
>cd spa-app
Directory Struture
******************************************************
Spa-app
Src
About.js
Home.js
Contact.js
App.js
Index.js
React Js
******************************************************
About.js
Home.js
Contact.js
React Js
App.js
//import BrowserRouter
//import NavLink
//import Route
render(){
return(
<Router>
<div>
<NavLink to="/"
exact strict
activeStyle={{color:"green"}}
style={{marginRight:100}}><b>About</b></NavLink>
<NavLink to="/home"
exact strict
activeStyle={{color:"green"}}
style={{marginRight:100}}><b>Home</b></NavLink>
<NavLink to="/contact"
exact strict
activeStyle={{color:"green"}}
style={{marginRight:100}}><b>Contact</b></NavLink>
<br></br><br></br>
</div>
</Router>
};
Index.js
import './index.css';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
React Js
// If you want your app to work offline and load faster, you can
change
serviceWorker.unregister();
React Js
Step 1.
******************************************
user : system
password : root
connectString : localhost/XE
table : auth
******************************************
step 2.
➢ Create-react-app parameters-app
Step 3.
➢ cd parameters-app
Step 4.
1) express
2) oracledb
3) body-parser
4) cors
Step 5.
**********************************************
parameters-app
server
server.js
React Js
**********************************************
server.js
app.use(cors());
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:false}));
app.post("/login",(req,res)=>{
oracledb.getConnection({user:"system",
password:"root",
connectString:"localhost/XE"},(err,c
onnection)=>{
else{
else{
if(records.rows.length>0){
res.send({"login":"success"});
}else{
res.send({"login":"fail"});
});
});
});
React Js
app.listen(8080);
Step 6.
➢ cd parameters-app/server
➢ node server
React Js
Step 7.
http://localhost:8080/login (POST)
React Js
Step 8.
Step 9.
**************************************
Parameters-app
Src
App.js
Login.js
Dashboard.js
*************************************
Login.js
constructor(){
super();
this.state = {
};
render(){
return(
<div>
<fieldset>
<legend>Login</legend>
<br></br><br></br>
<br></br><br></br>
<button onClick={this.login}>Login</button>
</fieldset>
</div>
};
login = ()=>{
React Js
axios.post("http://localhost:8080/login",{"uname":this.r
efs.uname.value,
"upwd":this.re
fs.upwd.value})
.then((posRes)=>{
this.props.history.push(`/dashboard/${this.s
tate.msg}`);
}else{
alert("Login Fail");
},(errRes)=>{
console.log(errRes);
});
};
};
Dashboard.js
render(){
return(
React Js
<div>
<h1 style={{color:"red"}}>{this.props.match.para
ms.param1}</h1>
</div>
};
};
App.js
render(){
return(
<div>
<Router>
</Router>
React Js
</div>
};
Step 10.
Terminal-1
➢ cd parameters-app/server
➢ node server
Terminal-2
➢ cd parameters-app
➢ yarn start
Output:
React Js
React Js
Lazy loading:
>cd Lazy-app
Directory Struture
******************************************************
Lazy-app
Src
Components
Mycomp.js
App.js
Index.js
******************************************************
Mycomp.js
};
App.js
import "./App.css";
render() {
return (
<div className="App">
<header className="App-header">
<div>another component</div>
<Suspense fallback={<div>Loading.....</div>}>
<MyComp />
</Suspense>
</header>
</div>
React Js
);
Index.js
import './index.css';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can
change
React Js
serviceWorker.unregister();
Output:
React Js
Chapter-14(Crud Operations)
CRUD Operations on MySQL DataBase
---------------------------------
SQL Queries
----------
Default Password : root
*******************************
host : localhost
user : root
Password: root
database: reactjs
table : employee
********************************
> cd crud-app
=> express
React Js
=> cors
=> mysql
=> body-parser
**************************
crud-app
server
server.js
*************************
> cd crud-app/server
Terminal-2
----------
> cd crud-app
*************************************
crud-app
server
server.js
src
Fetch.js
React Js
Insert.js
Update.js
Delete.js
*************************************
Server.js
**********
//import modules
//require() function used to import the modules
let express = require("express");
let mysql = require("mysql");
let cors = require("cors");
let bodyparser = require("body-parser");
Fetch.js
*********
<div>
<table border="1"
cellPadding="10px"
cellSpacing="10px"
align="center">
<thead
style={{backgroundColor:"grey"}}>
<tr>
<th>SNO</th>
<th>ENO</th>
<th>ENAME</th>
<th>ESAL</th>
</tr>
</thead>
<tbody>
{this.state.records.map((element,index)=>(
<tr>
<td>{index+1}</td>
<td>{element.eno}</td>
<td>{element.ename}</td>
<td>{element.esal}</td>
</tr>
))}
</tbody>
</table>
<hr style={{height:5,backgroundColor:"grey"}}></hr>
<br></br><br></br>
React Js
<Insert />
<hr style={{height:5,backgroundColor:"grey"}}></hr>
<br></br><br></br>
<Update />
<hr style={{height:5,backgroundColor:"grey"}}></hr>
<br></br><br></br>
<Delete />
</div>
)
};
};
Insert.js
**********
constructor(){
super();
this.state={
React Js
status:""
};
};
render(){
return(
<div>
<fieldset>
<legend>Insert</legend>
<input type="number"
ref="eno"/>
<br></br><br></br>
<input type="text"
ref="ename"/>
<br></br><br></br>
<input type="number"
ref="esal"/>
React Js
<br></br><br></br>
<button onClick={this.insert}>Insert</button>
<br></br>
<h1>{this.state.status}</h1>
</fieldset>
</div>
};
insert = ()=>{
let record = {
"eid":this.refs.eno.value,
"ename":this.refs.ename.value,
"esal":this.refs.esal.value
};
axios.post("http://localhost:8080/insert",
record)
.then((posRes)=>{
this.setState({
status:posRes.data.insert
React Js
})
},(errRes)=>{
console.log(errRes);
});
};
};
Update.js
*********
constructor(){
super();
this.state={
status : ""
};
};
render(){
return(
<div>
React Js
<fieldset>
<legend>Update</legend>
<input type="number"
ref="eid"
placeholder="employee id"/>
<br></br><br></br>
<input type="text"
ref="ename"
placeholder="employee name"/>
<br></br><br></br>
<input type="number"
ref="esal"
placeholder="Employee Sal"/>
<br></br><br></br>
<button onClick={this.update}>Update</button>
<h1>{this.state.status}</h1>
</fieldset>
</div>
};
update = ()=>{
React Js
let record = {
"eid":this.refs.eid.value,
"ename":this.refs.ename.value,
"esal":this.refs.esal.value
};
axios.put("http://localhost:8080/update",record)
.then((posRes)=>{
this.setState({
status :posRes.data.update
})
},(errRes)=>{
console.log(errRes);
});
};
};
Delete.js
**********
super();
this.state={
status : ""
};
};
render(){
return(
<div>
<fieldset>
<legend>Delete</legend>
<input type="number"
ref="eid"
placeholder="Employee ID"/>
<br></br><br></br>
<button onClick={this.remove}>Delete</button>
<h1>{this.state.status}</h1>
</fieldset>
</div>
)
};
remove = ()=>{
let record = {
"eid":this.refs.eid.value
};
axios.delete("http://localhost:8080/delete",{data:record})
.then((posRes)=>{
this.setState({
status:posRes.data.delet
})
React Js
},(errRes)=>{
console.log(errRes);
});
};
};
React Js
Chapter-15(Mini Project)
React Js
MySQL
MongoDB
SQLServer
module in miniproject.
authentication system.
Multiple Modules
- Index
- Login
- Dashboard
@About
@Home
@Portfolio
Implementation
--------------
mysql-essential-5.2.3-falcon-alpha-win32.msi
upwd varchar(20));
*********************************
host : localhost
user : root
password: root
database: reactjs
tables : login_details
about
*********************************
> mongod
> mongo
> db.createCollection("home");
> db.home.insert({sno:1,name:"reactjs"});
> db.home.find();
******************************
protocol : mongodb
port : 27017
host : localhost
database : reactjs
collection : home
******************************
******************************
User : sa
Password : 123
server : localhost
database : reactjs
table : portfolio
******************************
React Js
> cd miniproject-app
=> express
=> mysql
=> mssql
=> body-parser
=> cors
=> jwt-simple
*********************************************
miniproject-app =>server
config
mysql_properties.js
mysql_connection.js
mssql_properties.js
token.js
generateToken.js
auth.js
login
login.js
about
about.js
home
home.js
portfolio
portfolio.js
logout
logout.js
server.js
***********************************************
React Js
mysql_properties.js
let obj = {
host : "localhost",
React Js
user : "root",
password: "root",
database: "reactjs"
};
module.exports = obj;
mysql_connection.js
//import db details
let conn = {
getConnection : ()=>{
return mysql.createConnection(obj);
};
//export conn
module.exports = conn;
mssql_properties.js
let obj = {
React Js
server : "localhost",
user : "sa",
password: "123",
database: "reactjs"
};
module.exports = obj;
token.js
let obj = {
token : ""
};
module.exports = obj;
generateToken.js
return jwt.encode(data,password);
};
React Js
module.exports = my_fun;
auth.js
console.log(c_token);
console.log(s_token);
next();
}else{
res.send("UnAuthorized User....!");
};
module.exports = auth;
React Js
login.js
module.exports =
require("express").Router().post("/",(req,res)=>{
(err,records,fields)=>{
if(records.length>0){
uname:req.body.uname,
upwd:req.body.upwd
},"[email protected]");
obj.token = token;
res.send({login:"success",token:token});
}else{
res.send({login:"fail"});
});
});
about.js
module.exports =
require("express").Router().get("/",[auth],(req,res)=>{
connection.query(`select * from
about`,(err,records,fields)=>{
res.send(records);
});
});
home.js
React Js
module.exports =
require("express").Router().get("/",[auth],(req,res)=>{
nareshIT.connect("mongodb://localhost:27017/reactjs",(err,db)=
>{
db.collection("home").find().toArray((err,array)=>{
res.send(array);
});
});
});
portfolio.js
module.exports =
require("express").Router().get("/",[auth],(req,res)=>{
React Js
mssql.connect(obj,(err)=>{
if(err){
console.log("Error...!");
}else{
request.query(`select * from
portfolio`,(err,records)=>{
if(err){
console.log("Error...!");
}else{
res.send(records);
mssql.close();
});
});
});
logout.js
module.exports =
require("express").Router().get("/",[auth],(req,res)=>{
obj.token = "";
res.send({logout:"success"});
});
server.js
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:false}));
app.use(cors());
app.use("/login",require("./login/login"));
app.use("/about",require("./about/about"));
app.use("/home",require("./home/home"));
app.use("/portfolio",require("./portfolio/portfolio"));
app.use("/logout",require("./logout/logout"));
app.listen(8080);
Step 9:
> cd miniproject-app
> cd server
Step 10.
Step 11.
> cd miniproject-app
Step 12.
*************************************
Miniproject-app
src
Login.js
About.js
Home.js
Portfolio.js
***************************************
Login.js
import "./App.css";
render(){
return(
<div className="App">
<fieldset>
<legend>Login</legend>
React Js
<label
style={{marginRight:40}}>Uname:</label>
<input type="text"
ref="uname"
placeholder="User Name"></input>
<br></br><br></br>
<label
style={{marginRight:40}}>Upwd:</label>
<input type="password"
ref="upwd"
placeholder="Password"></input>
<br></br><br></br>
<button onClick={this.login}>Login</button>
</fieldset>
</div>
login = ()=>{
axios.post("http://localhost:8080/login",
'uname':this.refs.uname.value,
'upwd':this.refs.upwd.value
React Js
}).then((posRes)=>{
window.localStorage.setItem("login_details",str);
//navigate to Dashboard
this.props.history.push('/dashboard')
},(errRes)=>{
console.log(errRes);
});
};
};
About.js
import "./App.css";
constructor(){
super();
this.state = {
};
React Js
render(){
return(
<div className="App">
<h1 style={{color:"red"}}>{this.state.res}</h1>
</div>
};
componentDidMount(){
console.log(obj.token);
axios.get("http://localhost:8080/about",{headers:{token:obj.toke
n}})
.then((posRes)=>{
console.log(posRes);
this.setState({
res:str
})
},(errRes)=>{
React Js
console.log(errRes);
});
};
Home.js
import "./App.css";
constructor(){
super();
this.state = {
};
render(){
return(
<div className="App">
<h1
style={{color:"green"}}>{this.state.res}</h1>
</div>
)
React Js
};
componentDidMount(){
let token =
JSON.parse(window.localStorage.getItem("login_details"))
.token;
axios.get("http://localhost:8080/home",{headers:{token:token}}).
then((posRes)=>{
this.setState({
res:JSON.stringify(posRes.data)
});
},(errRes)=>{
console.log(errRes);
});
};
};
Portfolio.js
import "./App.css";
constructor(){
React Js
super();
this.state = {
};
render(){
return(
<div className="App">
<h1 style={{color:"blue"}}>{this.state.res}</h1>
</div>
};
componentDidMount(){
let token =
JSON.parse(window.localStorage.getItem("login_details"))
.token;
axios.get("http://localhost:8080/portfolio",
{headers:{token:token}}).then((posRes)=>{
this.setState({
res:JSON.stringify(posRes.data)
});
React Js
},(errRes)=>{
console.log(errRes);
});
};
};
Step 13.
> cd miniproject-app
Step 14.
*************************************
Miniproject-app
Src
Dashboard.js
**************************************
Dashboard.js
//import Route
render(){
return(
<Router>
<div>
<NavLink to="/about"
activeStyle={{color:"green"}}
exact strict
style={{marginRight:100}}>About</NavLink>
<NavLink to="/home"
activeStyle={{color:"green"}}
React Js
exact strict
style={{marginRight:100}}>Home</NavLink>
<NavLink to="/portfolio"
activeStyle={{color:"green"}}
exact strict
style={{marginRight:100}}>Portfolio</NavLink>
<button
onClick={this.logout}>Logout</button>
<br></br><br></br>
</div>
</Router>
) };
logout = ()=>{
axios.get("http://localhost:8080/logout",{headers:{"token":token
}})
.then((posRes)=>{
window.localStorage.removeItem("login_details");
this.props.history.push('/')
},(errRes)=>{
console.log(errRes);
});
};};
Step 15.
*************************************
Miniproject-app
Src
Main.js
React Js
**************************************
Main.js
render(){
return(
<Router>
<div>
</div>
</Router>
};
Step 16.
React Js
*************************************
Miniproject-app
Src
index.js
**************************************
index.js
import './index.css';
// If you want your app to work offline and load faster, you can
change
serviceWorker.unregister();
React Js
Step 17.
//Terminal-1
> cd miniproject-app
> cd server
//Terminal-2
> mongod
//Terminal-3
Chapter-16(Crud Operations-Thunk)
CRUD Operations on MySQL DataBase
---------------------------------
React Js
Ex.
MySQL
1) express
2) mysql
3) body-parser
4) cors
React Js
> cd MySQL
****************************************
host : localhost
user : root
password : root
database : fullstack
table : products
****************************************
*********************************
MySQL
config
React Js
db_properties.js
db_connection.js
fetch
fetch.js
insert
insert.js
update
update.js
delete
delete.js
server.js
************************************
db_properties.js
let conn = {
getConnection : ()=>{
return mysql.createConnection(obj);
};
module.exports = conn;
db_connection.js
let obj = {
host : "localhost",
user : "root",
password : "root",
database : "fullstack_9pm"
};
module.exports = obj;
fetch.js
connection.query(`select * from
products`,(err,records,fields)=>{
else{
res.send(records);
});
});
module.exports = fetch;
insert.js
'${req.body.p_name}',
${req.body.p_cost})`,(err,result)=>{
else{
res.send({"insert":"success",record:{"p_id":`${req.body.p_id}`,
React Js
"p_name":`${req.body.p_name}`,
"p_cost":`${req.body.p_cost}`}
});
});
});
module.exports = insert;
update.js
else{
res.send({update:"success",record:{"p_id":req.body.p_id,
"p_name":req.body.p_name,
React Js
"p_cost":req.body.p_cost}});
});
});
module.exports = update;
delete.js
else{
res.send({delete:"success","p_id":req.body.p_id});
});
});
module.exports = remove;
server.js
app.use(cors());
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:false}));
app.use("/fetch",require("./fetch/fetch"));
app.use("/insert",require("./insert/insert"));
app.use("/update",require("./update/update"));
app.use("/delete",require("./delete/delete"));
app.listen(8080);
> cd MySQL
8) switch to crud-app
> cd crud-app
Terminology
Actions
-------
Ex.
Reducer
-------
=> redux-thunk
=> redux
=> react-redux
=> bootstrap
=> react-bootstrap
=> axios
React Js
****************************
public
index.html
************************
Index.html
<script
src="https://unpkg.com/react/umd/react.production.min.js"
crossorigin></script>
<script
src="https://unpkg.com/react-dom/umd/react-
dom.production.min.js"
crossorigin></script>
React Js
<script
src="https://unpkg.com/react-bootstrap@next/dist/react-
bootstrap.min.js"
crossorigin></script>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootst
rap.min.css"
integrity="sha384-
Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh
"
crossorigin="anonymous"
/>
<script
src="https://kit.fontawesome.com/a076d05399.js"></script>
**********************************
src
actions
actions.js
React Js
*********************************
actions.js
/***************************************************/
return (dispatch)=>{
return axios.get("http://localhost:8080/fetch")
.then((posRes)=>{
dispatch( fun_one(posRes.data) );
},(errRes)=>{
console.log(errRes);
});
};
return {type:"FETCH",value:records};
};
/****************************************************/
/*****************************************************/
return (dispatch)=>{
return
axios.delete("http://localhost:8080/delete",{data:record})
.then((posRes)=>{
dispatch(fun_two(posRes.data));
},(errRes)=>{
console.log(errRes);
});
};
};
return {type:"DELETE",value:result};
};
/**************************************************/
/************************************************ */
return (dispatch)=>{
return axios.post("http://localhost:8080/insert",record)
.then((posRes)=>{
dispatch(fun_three(posRes.data));
},(errRes)=>{
React Js
console.log(errRes);
});
};
};
/******************************************** */
/*********************************************** */
return (dispatch)=>{
return axios.put("http://localhost:8080/update",record)
.then((posRes)=>{
dispatch(fun_four(posRes.data));
},(errRes)=>{
console.log(errRes);
});
};
};
/********************************************** */
****************************************
src
reducer
reducer.js
****************************************
reducer.js
const initialState = {
data : []
};
switch(action.type){
case "FETCH":
state.data = [];
return{
...state,
data : state.data.concat(action.value)
}
React Js
break;
case "INSERT":
case "UPDATE":
case "DELETE":
return{
...state,
status : action.value
break;
return state;
};
****************************************
src
index.js
****************************************
React Js
index.js
import './index.css';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can
change
React Js
serviceWorker.unregister();
***********************************
src
App.js
**********************************
App.js
constructor(){
super();
this.state = {
React Js
status : false,
insertPopup : false,
updatePopup : false
};
};
componentDidMount(){
this.props.getProducts();
};
showPopup = (msg)=>{
this.setState({
updatePopup:false,
insertPopup : true,
status : true
})
}else{
this.setState({
insertPopup : false,
updatePopup : true,
status : true
})
}
React Js
};
closePopup = ()=>{
this.setState({
status : false
})
};
deleteRecord = (id)=>{
this.props.deleteRecord(id);
};
save = ()=>{
if(this.state.insertPopup){
"p_name" : this.refs.p_name.value,
"p_cost" : this.refs.p_cost.value};
this.props.addProduct(obj);
else if(this.state.updatePopup){
"p_name" : this.refs.p_name.value,
React Js
"p_cost" : this.refs.p_cost.value};
this.props.updateProduct(obj);
this.closePopup();
this.closePopup();
};
render(){
return(
<Button className="float-right"
onClick={()=>{ this.showPopup("insert")
}}>Add <i className="fas fa-plus"></i>
</Button>
<Modal show={this.state.status}
onHide={this.closePopup}
size="sm"
centered>
React Js
<Modal.Header closeButton>
<Modal.Title>Add/Update</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form>
<Form.Group>
<Form.Label>P_ID</Form.Label>
<Form.Control type="number"
placeholder="Enter P_ID"
ref="p_id"></Form.Control>
</Form.Group>
<Form.Group>
<Form.Label>P_NAME</Form.Label>
<Form.Control type="text"
placeholder="Enter P_NAME"
ref="p_name"></Form.Control>
</Form.Group>
<Form.Group>
React Js
<Form.Label>P_COST</Form.Label>
<Form.Control type="number"
placeholder="Enter P_COST"
ref="p_cost"></Form.Control>
</Form.Group>
</Form>
</Modal.Body>
<Modal.Footer>
<Button varient="danger"
onClick={this.closePopup}>Close</Button>
</Modal.Footer>
</Modal>
<Table bordered
variant="dark"
size="sm"
React Js
hover
striped
className="text-center">
<thead>
<tr>
<th>SNO</th>
<th>ID</th>
<th>NAME</th>
<th>COST</th>
<th>EDIT</th>
<th>DELETE</th>
</tr>
</thead>
<tbody>
{this.props.data.map((element,index)=>(
<tr key={index}>
<td>{index+1}</td>
<td>{element.p_id}</td>
<td>{element.p_name}</td>
<td>{element.p_cost}</td>
React Js
</tr>
))}
</tbody>
</Table>
</Container>
};
if(state.hasOwnProperty("status")){
let id = state.data.findIndex((element,index)=>{
});
React Js
state.data.splice(id,1);
state.data.push(state.status.record);
state.data.forEach((element,index)=>{
if(element.p_id == state.status.record.p_id){
element.p_name = state.status.record.p_name;
element.p_cost = state.status.record.p_cost;
});
return{
data : state.data,
status : state.status
}
React Js
};
return{
deleteRecord : (id)=>{
dispatch(actions.deleteProduct({"p_id":id})) },
addProduct : (record)=>{
dispatch(actions.addProduct(record)) },
updateProduct : (record)=>{
dispatch(actions.updateProduct(record)) }
};
Output:
React Js
Chapter-17(MiniProject-Saga)
Step 1) install MongoDB
website :
https://www.mongodb.com/dr/fastdl.mongodb.org/win32/mongodb-
win32-x86_64-2012plus-4.2.8-signed.msi/download
file : mongodb-win32-x86_64-2012plus-4.2.8-signed.msi
c:/data/db
********************************************
MongoDB Queries
********************************************
> mongod
> mongo
> db.createCollection("login_details");
> db.createCollection("angular");
> db.createCollection("react");
> db.createCollection("deno");
> db.login_details.insert({"uname":"admin","upwd":"admin"});
> db.login_details.find().pretty();
> db.angular.find().pretty();
> db.react.find().pretty();
> db.deno.find().pretty();
****************************************************
host : localhost
protocol : mongodb
port : 27017
database : miniproject@4pm
collections : login_details
angular
react
deno
****************************************************
=> express
=> cors
React Js
=> body-parser
=> jwt-simple
**********************************
miniproject@4pm
config
generateToken.js
token.js
auth.js
React Js
login
login.js
angular
angular.js
react
react.js
deno
deno.js
logout
logout.js
server.js
**********************************
generateToken.js
React Js
return jwt.encode(data,password);
};
module.exports = getnerateToken;
token.js
let obj = {
"token":""
};
module.exports = obj;
auth.js
//this file used to compare the client side token with the
server side token (middleware)
if(c_token == obj.token){
next();
}else{
};
module.exports = auth;
login.js
nareshIT.connect("mongodb://localhost:27017/authproject",(err,db
)=>{
else{
db.collection("login_details")
.find({"uname":req.body.uname,"upwd":req.body.upwd})
.toArray((err,array)=>{
else{
if(array.length>0){
let token =
generateToken({"uname":req.body.uname,
"upwd":req.body.upwd},"[email protected]");
obj.token = token;
React Js
res.send({login:"success",token:token})
}else{
res.send({login:"fail"});
});
});
});
module.exports = login;
angular.js
let angular =
require("express").Router().get("/",[require("../config/auth")],
(req,res)=>{
nareshIT.connect("mongodb://localhost:27017/authproject",(err,db
)=>{
else{
db.collection("angular").find().toArray((err,array)=>{
React Js
else{
res.send(array);
});
});
});
module.exports = angular;
react.js
let react =
require("express").Router().get("/",[require("../config/auth")],
(req,res)=>{
nareshIT.connect("mongodb://localhost:27017/authproject",(err,db
)=>{
else{
db.collection("react").find().toArray((err,array)=>{
else{
React Js
res.send(array);
});
});
});
module.exports = react;
deno.js
let deno =
require("express").Router().get("/",[require("../config/auth")],
(req,res)=>{
nareshIT.connect("mongodb://localhost:27017/authproject",(err,db
)=>{
else{
db.collection("deno").find().toArray((err,array)=>{
else{
res.send(array);
}
React Js
});
});
});
module.exports = deno;
logout.js
let logout =
require("express").Router().get("/",[require("../config/auth")],
(req,res)=>{
obj.token = "";
res.send({"logout":"success"});
});
module.exports = logout;
server.js
app.use(cors());
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:false}));
React Js
app.use("/login",require("./login/login"));
app.use("/angular",require("./angular/angular"));
app.use("/react",require("./react/react"));
app.use("/deno",require("./deno/deno"));
app.use("/logout",require("./logout/logout"));
app.listen(8085);
> cd auth-proj
=> axios
=> redux
=> react-redux
=> redux-saga
=> react-router-dom
=> @material-ui/core
=> @material-ui/icons
<!DOCTYPE html>
<html lang="en">
<head>
<meta
name="description"
/>
<!--
-->
React Js
<!--
-->
<link rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500
,700&display=swap" />
<link rel="stylesheet"
href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>
<title>React App</title>
</head>
<body>
React Js
<div id="root"></div>
<!--
The build step will place the bundled scripts into the
<body> tag.
-->
</body>
</html>
********************************
auth-proj
src
action
action.js
********************************
action.js
function login_call(data){
return axios.post("http://localhost:8085/login",data);
};
function* login(action) {
if(res.data.login == "success"){
React Js
window.localStorage.setItem("login_details",JSON.stringify(res.d
ata));
//yield call(forwardTo,"/dashboard");
//this.props.history.push("/dashboard");
window.location.href = `/dashboard`
}else{
//navigate to Error
console.log("error");
};
function angular_call(){
};
React Js
function *angular(action){
yield put({type:"ANGULAR",value:res.data});
function react_call(){
return
axios.get("http://localhost:8085/react",{headers:{token :
obj.token}});
};
function *react(action){
yield put({type:"REACT",value:res.data});
};
function deno_call(){
React Js
return
axios.get("http://localhost:8085/deno",{headers:{token :
obj.token}});
};
function *deno(action){
};
function logout_call(){
return
axios.get("http://localhost:8085/logout",{headers:{token :
obj.token}});
};
React Js
function *logout(action){
if(res.data.logout == "success"){
window.localStorage.removeItem("login_details");
yield put({type:"LOGOUT",value:res});
window.location.href = `/`
}else{
console.logout("error");
};
yield takeLatest("LOGOUT_ACTION",logout );
};
function forwardTo(location) {
history.push(location);
React Js
****************************************
auth-proj
reducer
reducer.js
***************************************
reducer.js
switch(action.type){
case "LOGIN":
return{
...state,
login : action.value
break;
case "ANGULAR":
case "REACT":
case "DENO":
return{
...state,
React Js
msg : action.value
break;
case "LOGOUT":
return{
...state
break;
};
return state;
};
index.js
import "./index.css";
sagaMiddleware.run(main_fun);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
****************************************
auth-proj
src
login.js
dashboard.js
angular.js
reactjs.js
React Js
deno.js
App.s
***************************************
login.js
render(){
return(
<div>
<fieldset>
<legend>Login</legend>
<input type="text"
placeholder="user name"
ref="uname"/>
<br></br><br></br>
<input type="password"
placeholder="user password"
ref="upwd"/>
<br></br><br></br>
React Js
<button
onClick={()=>{this.props.login({"uname":this.refs.uname.value,
"upwd":this.refs.upwd.value})}}>Login</button>
</fieldset>
</div>
};
};
//subscribe
console.log(state);
};
//dispatch
return{
login : (obj)=>{
dispatch({type:"LOGIN_ACTION",value:obj}) }
};
React Js
dashboard.js
render(){
return(
<Router>
<NavLink to="/angular"
activeStyle={{color:"red"}}
exact strict
style={{marginRight:100}}>Angular</NavLink>
<NavLink to="/reactjs"
React Js
activeStyle={{color:"red"}}
exact strict
style={{marginRight:100}}>React</NavLink>
<NavLink to="/deno"
activeStyle={{color:"red"}}
exact strict
style={{marginRight:100}}>Deno</NavLink>
<button
onClick={this.props.logout}>Logout</button>
<br></br><br></br>
</Router>
};
React Js
return{
};
return{
logout : ()=>{
console.log("hello");
dispatch({type:"LOGOUT_ACTION",value:{}}) }
};
angular.js
componentDidMount(){
this.props.getAngularData();
};
render(){
return(
<div>
{JSON.stringify(this.props.angular)}
</div>
};
console.log(state);
return{
angular : state
};
return{
getAngularData : ()=>{
dispatch({type:"ANGULAR_ACTION",value:{}}) }
}
React Js
reactjs.js
componentDidMount(){
this.props.getReactModuleData();
};
render(){
return(
<div>
{JSON.stringify(this.props.msg)}
</div>
};
return{
msg : state
}
React Js
};
return{
getReactModuleData : ()=>{
dispatch({type:"REACT_ACTION",value:{} }) }
};
deno.js
componentDidMount(){
this.props.getDenoData();
};
render(){
return(
<div>
{JSON.stringify(this.props.msg)}
</div>
}
React Js
};
return{
msg : state
};
return{
getDenoData : ()=>{
dispatch({type:"DENO_ACTION",value:{}}) }
};
App.js
render(){
return(
React Js
<Router>
</Router>
}};
Step 14)
//Terminal-1
> cd miniproject-app
> cd server
//Terminal-2
> mongod
//Terminal-3
>cd auth-proj
Chapter-18(Validations Example)
In this example we will store the data into database (SQLServer)
*************************************************
user : sa
password : 123
server : localhost
database : reactjs
table : registration
************************************************
> cd registration-app
=> express
=> cors
=> body-parser
=> axios
****************************************
registration-app
server
server.js
****************************************
server.js
//ports communication
app.use(cors());
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:false}));
app.post("/registration",(req,res)=>{
//connect to SQLServer
mssql.connect({
user:"sa",
password:"123",
server:"localhost",
React Js
database:"reactjs"
},(err)=>{
else{
else{
res.send({registration:"success"});
})
});
});
app.listen(8080);
> cd registration-app
> cd server
Terminal-2
----------
> cd registration-app
App.js
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
constructor(){
super();
this.state = {
"country":"",
"countryValid":false,
React Js
"Female":false,
"Male":false,
"genderValid":false,
"English":false,
"Hindi":false,
"Telugu":false,
"fname":"",
"lname":"",
"email":"",
"dob":"",
"dobValid":false,
"emailValid":false,
"fnameValid":false,
"lnameValid":false,
"formValid":false,
"languagesValid":false,
"formErrors":{"fname":"",
"lname":"",
"email":"",
"dob":"",
"languages":"",
"gender":"",
React Js
"country":""}
};
};
register = (event)=>{
let gender="";
if(this.state[key]===true){
languages.push(key);
};
gender = key
};
let record = {
"fname":this.state.fname,
"lname":this.state.lname,
React Js
"email":this.state.email,
"dob":this.state.dob,
"gender":gender,
"languages":languages,
"country":this.state.country
};
axios.post("http://localhost:8080/registration",record)
.then((posRes)=>{
console.log(posRes);
},(errRes)=>{
console.log(errRes);
});
};
handleChange = (event)=>{
switch(name){
case "English":
React Js
this.setState(prevState=>({
English : !prevState.English
}),()=>{this.validateForm(name,value)});
break;
case "Telugu":
this.setState(prevState=>({
Telugu : !prevState.Telugu
}),()=>{this.validateForm(name,value)});
break;
case "Hindi":
this.setState(prevState=>({
Hindi : !prevState.Hindi
}),()=>{this.validateForm(name,value)});
break;
case "Gender":
this.setState(prevState=>({
Male : !prevState.Male
}),()=>{this.validateForm(name,value)});
}else{
this.setState(prevState=>({
Female : !prevState.Female
React Js
}),()=>{this.validateForm(name,value)});
break;
default:
this.setState({
[name]:value
},()=>{this.validateForm(name,value)});
break;
};
validateForm(name,value){
switch(name){
case "country":
React Js
l_countryValid = value.length<0;
break;
case "Gender":
break;
case "fname":
l_fnameValid = value.length>6;
break;
case "lname":
l_lnameValid = value.length>3;
break;
case "email":
l_emailValid = value.match(/^([\w.%+-]+)@([\w-
]+\.)+([\w]{2,})$/i);;
React Js
break;
case "dob":
l_dobValid= value.length>8;
break;
case "English":
case "Telugu":
case "Hindi":
l_formErrors.languages = l_languagesValid?"":"s
elect at least one language"
break;
};
this.setState({
fnameValid:l_fnameValid,
lnameValid:l_lnameValid,
emailValid:l_emailValid,
dobValid:l_dobValid,
React Js
languagesValid:l_languagesValid,
genderValid : l_genderValid,
formErrors:l_formErrors
},this.finalFun );
};
finalFun(){
this.setState({
formValid : this.state.fnameValid,
formValid : this.state.lnameValid,
formValid : this.state.dobValid,
formValid : this.state.emailValid,
formValid : this.state.languagesValid,
formValid : this.state.genderValid
})
};
render(){
return(
<div className="col-md-4">
<label>First Name</label>
</div>
<div className="col-md-8">
<input type="text"
name="fname"
value={this.state.fname}
required
onChange={this.handleChange}></in
put>
<h5 style={{color:"red"}}>{this.stat
e.formErrors.fname}</h5>
</div>
</div>
<div className="row">
React Js
<div className="col-md-4">
<label>Last Name</label>
</div>
<div className="col-md-8">
<input type="text"
name="lname"
value={this.state.lname}
required
onChange={this.handleChange}></in
put>
<h5 style={{color:"red"}}>{this.stat
e.formErrors.lname}</h5>
</div>
</div>
<div className="row">
<div className="col-md-4">
<label>Email</label>
</div>
React Js
<div className="col-md-8">
<input type="email"
name="email"
value={this.state.email}
placeholder="Enter Email"
required
onChange={this.handleChange}></in
put>
<h5 style={{color:"red"}}>{this.stat
e.formErrors.email}</h5>
</div>
</div>
<div className="row">
<div className="col-md-4">
<label>Date Of Birth</label>
</div>
<div className="col-md-8">
<input type="date"
name="dob"
value={this.state.dob}
React Js
required
onChange={this.handleChange}></in
put>
<h5 style={{color:"red"}}>{this.stat
e.formErrors.dob}</h5>
</div>
</div>
<div className="row">
<div className="col-md-4">
<label>Languages</label>
</div>
<div className="col-md-8">
<input type="checkbox"
checked={this.state.English}
name="English"
value="English"
onChange={this.handleChange}/> <b
>English</b>
<input type="checkbox"
className="ml-1"
React Js
name="Telugu"
value="Telugu"
checked={this.state.Telugu}
onChange={this.handleChange}/> <b
>Telugu</b>
<input type="checkbox"
className="ml-1"
name="Hindi"
value="Hindi"
checked={this.state.Hindi}
onChange={this.handleChange}/> <b
>Hindi</b>
</div>
<h5 style={{color:"red"}}>{this.state.formEr
rors.languages}</h5>
</div>
<br></br>
<div className="row">
<div className="col-md-4">
<label>Gender</label>
</div>
<div className="col-md-8">
React Js
<input type="radio"
name="Gender"
value="Male"
checked={this.state.Male}
onChange={this.handleChange}/> <b
>Male</b>
<input type="radio"
name="Gender"
value="Female"
checked={this.state.Female}
onChange={this.handleChange}
className="ml-2"/> <b>Female</b>
</div>
</div>
<br></br><br></br>
<div className="row">
<div className="col-md-4">
Country
</div>
<div className="col-md-8">
<select name="country"
React Js
value={this.state.country}
onChange={this.handleChange}>
<option value="india">India</option>
<option value="usa">USA</option>
<option value="uk">London</option>
</select>
</div>
</div>
<br></br>
<div className="row">
<div className="col-md-4"></div>
<div className="col-md-8">
disabled={!this.state.formValid}
onClick={this.register}>Register</button>
</div></div>
</div></div>
};
};
OutPut:
React Js
React Js
(MYSQL-MSSQL-MONGODB)
Ex.
mysql-essential-5.2.3-falcon-alpha-win32.msi
Queries:
**********************************************
host : localhost
user : root
password : root
database : crud
table : products
********************************************
Ex.
MySQL_CRUD
4) switch to MySQL_CRUD
React Js
> cd MySQL_CRUD
=> mysql
=> cors
=> body-parser
=> express
GET
POST
PUT
DELETE
HEAD
**************************************
MySQL_CRUD
config
db_properties.js
db_connection.js
fetch
fetch.js
insert
insert.js
update
update.js
delete
delete.js
server.js
***************************************
• "fetch.js" file used to create the GET Request. (fetch the data
from products table).
• "insert.js" file used to create the POST Request (insert the
record into products table).
• "update.js" file used to create the PUT Request (update the
record into products table).
• "delete.js" file used to create the DELETE Request (delete the
record from products table).
db_properties.js
let obj = {
host : "localhost",
user : "root",
password : "root",
database : "crud"
};
module.exports = obj;
db_connection.js
let conn = {
getConnection : ()=>{
return mysql.createConnection(obj);
}
React Js
};
module.exports = conn;
fetch.js
connection.query(`select * from
products`,(err,records,fields)=>{
else{
res.send(records);
});
});
module.exports = fetch;
insert.js
(err,result)=>{
else{
res.send({insert:"success"});
});
});
module.exports = insert;
update.js
(err,result)=>{
else{
res.send({update : "success"});
});
React Js
});
module.exports = update;
delete.js
else{
res.send({delete:"success"});
});
});
module.exports = remove;
server.js
app.use(cors());
app.use(bodyparser.json());
React Js
app.use(bodyparser.urlencoded({extended:false}));
app.use("/fetch",require("./fetch/fetch"));
app.use("/insert",require("./insert/insert"));
app.use("/update",require("./update/update"));
app.use("/delete",require("./delete/delete"));
app.listen(8080);
> cd MySQL_CRUD
*****************************
React Js
-----------------------
MongoDB_CRUD
2) switch to MongoDB_CRUD
> cd MongoDB_CRUD
> mongod
> mongo
> db.createCollection("products");
> db.products.insert({"p_id":111,
"p_name":"p_one",
"p_cost":10000});
> db.products.find();
React Js
********************************************
host : localhost
port : 27017
protocol : mongodb
database : crud
collection : products
********************************************
=> express
=> cors
=> body-parser
*************************************
MongoDB_CRUD
fetch
fetch.js
insert
insert.js
update
update.js
delete
delete.js
server.js
*************************************
• fetch.js file used to create the GET Request (fetch the data
from products collection)
• insert.js file used to create the POST Request (insert the
record into products collection)
• update.js file used to create the PUT Request (update the
record present in products collection)
React Js
fetch.js
nareshIT.connect("mongodb://localhost:27017/crud",(err,db)=>{
else{
db.collection("products").find().toArray((err,array)=>{
else{
res.send(array);
})
});
});
module.exports = fetch;
React Js
insert.js
nareshIT.connect("mongodb://localhost:27017/crud",(err,db)=>{
else{
db.collection("products").insertOne({"p_id":req.body.p_id,
"p_name":req.body.p_name,
"p_cost":req.body.p_cost},(err,result)=>{
else{
res.send({insert : "success"});
});
});
});
module.exports = insert;
React Js
update.js
nareshIT.connect("mongodb://localhost:27017/crud",(err,db)=>{
else{
db.collection("products").updateOne({"p_id":req.body.p_id},
{$set:{"p_name":req.body.p_name,"p_cost":req.body.p_cost}}
(err,result)=>{
else{
res.send({update : "success"});
});
});
});
React Js
module.exports = update;
delete.js
nareshIT.connect("mongodb://localhost:27017/crud",(err,db)=>{
else{
db.collection("products").deleteOne({"p_id":req.body.p_id},(err,
result)=>{
else{
res.send({delete : "success"});
});
});});
module.exports = remove;
server.js
app.use(cors());
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:false}));
app.use("/fetch",require("./fetch/fetch"));
app.use("/insert",require("./insert/insert"));
app.use("/update",require("./update/update"));
app.use("/delete",require("./delete/delete"));
app.listen(8080);
**********************************
React Js
-------------------------
1) install SQLServer
Ex.
*******************************************
user : sa
password : 123
database : crud
table : products
******************************************
4) switch to MSSQL_CRUD
> cd MSSQL_CRUD
=> express
=> cors
=> body-parser
=> [email protected]
React Js
***********************************
MSSQL_CRUD
config
db_properties.js
fetch
fetch.js
insert
insert.js
update
update.js
delete
delete.js
server.js
***********************************
db_properties.js
let obj = {
server : "localhost",
React Js
user : "sa",
password : "123",
database : "crud"
};
module.exports = obj;
fetch.js
mssql.connect(obj,(err)=>{
else{
request.query(`select * from
products`,(err,records)=>{
else{
res.send(records.recordset);
mssql.close();
});
}
React Js
});
});
module.exports = fetch;
insert.js
mssql.connect(obj,(err)=>{
else{
'${req.body.p_name}',
${req.body.p_cost})`,(err,result)=>{
else{
res.send({insert : "success"});
mssql.close();
React Js
});
});
});
module.exports = insert;
update.js
mssql.connect(obj,(err)=>{
else{
(err,result)=>{
else{
res.send({update : "success"});
mssql.close();
React Js
});
});
});
module.exports = update;
delete.js
mssql.connect(obj,(err)=>{
else{
else{
res.send({delete:"success"});
mssql.close();
});
}
React Js
});
});
module.exports = remove;
server.js
app.use(cors());
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:false}));
app.use("/fetch",require("./fetch/fetch"));
app.use("/insert",require("./insert/insert"));
app.use("/update",require("./update/update"));
app.use("/delete",require("./delete/delete"));
app.listen(8080);
> cd MSSQL_CRUD