Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Day24 ReactJS SPA Hooks ClassComponents

Uploaded by

Warstilide49
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Day24 ReactJS SPA Hooks ClassComponents

Uploaded by

Warstilide49
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Narasimha

Sr. Corporate Trainer, Mentor


Narasimha
Sr. Corporate Trainer, Mentor
Week5 – React JS
Day21 : Introduction, Components
Day22 : Events, State, Apply Styles
Day23 : Server Calls / AJAX, Form Validations
Day24 : SPA, Redux
Day25 : React Hooks, Testing
Narasimha
Sr. IT Trainer/Consultant
Narasimha
Sr. IT Trainer/Consultant
What is SPA?

• A single-page application (SPA) is a web application or


website that interacts with the user by dynamically
rewriting the current web page with new content.
• It updates partial, instead of loading entire new pages
• The goal is faster transitions that make the website feel
more like a desktop app.
Narasimha
Sr. IT Trainer/Consultant
Steps to Implement

1. Install react-router-dom package


2. Import the required items in index.js
3. Configure the routes with corresponding
components
4. Preparing Hyperlinks using Link tag
5. Provide routing details in root.render()
method.
Implementation

Install react-router-dom module


npm install react-router-dom --save

Import the required items in index.js


import {Routes, Route, Link, BrowserRouter as Router }
from 'react-router-dom';
Configure the routes and Prepare Hyperlinks
const routing = (
<Router>
<Link to="/">Home</Link>
<Link to="/Emps">Employees</Link>

<Routes>
<Route path="/" element= { <App /> } />
<Route path="/Emps" element= { <Emps /> } />
…..
</Routes>
</Router>
);
Routing details in ReactDOM.render()
const root =
ReactDOM.createRoot(document.getElementById('root’));

root.render(
<React.StrictMode>
{routing}
</React.StrictMode>
);
Narasimha
Sr. IT Trainer/Consultant
How to handle invalid route?
<Route path="*" element= { <NotFound /> } />

function NotFound(){
return <div>
………
</div>;
};
export default NotFound;
Narasimha
Sr. IT Trainer/Consultant
How to handle route parameters?
<Route path="/Details/:id" element= { <Details /> } />

<Link to={"/Details/" + item.empno}>Details</Link>

import { Link, useParams } from 'react-router-dom';

function Details(props)
{
const { id } = useParams();
…………………
}

export default Details;


Narasimha
Sr. IT Trainer/Consultant
How to implement nested routing?

Index.js
<Route path="/Admin" element= { <Admin /> }>
<Route index element= { <AdminHome /> } />
<Route path="Projects" element= { <Projects /> } />
<Route path="Customers" element= { <Customers /> } />
</Route>
How to implement nested routing?

function Admin()
{
return (
<div>
<h3>This is Admin Component</h3>
<Link to="">Admin Home</Link> |
<Link to="Projects">Projects</Link> |
<Link to="Customers">Customers</Link> |
<Outlet />
</div> );
}
Narasimha
Sr. IT Trainer/Consultant
Programmatic Navigations
import { useNavigate } from "react-router-dom";
let navigate = useNavigate();
navigate("/Emps");

window.location.replace(url);
Hands-On Implementation
Narasimha
Sr. IT Trainer/Consultant
Class Components
import React from 'react';

class App extends React.Component


{
render() {
return (
<div> Hello World</div> );
}
}
export default App;
Class Components

• Always start component names with a capital letter.


– Eg: App, Dept, Emps
• Every component class should inherits from
“Component” class.
• Every component class should have render() method
which returns react element (UI Logic).
• We need to Export component class so that we can
import from other components.
Class Components
import React from 'react';

class App extends React.Component


{
render() {
return (
<div> Hello World</div> );
}
}
export default App;
State in Class Components
class Demo extends React.Component
{
constructor() {
// Initialize State
this.state = { name : "Scott" };
this.button1Click = this.button1Click.bind( this );
}

button1Click() {
this.setState( { name : "Scott" } );
// Update State
}
}
State in Class Components
class Demo extends React.Component
{
constructor() {
// Initialize State
this.state = { name : "Scott" };
this.buttonClick = this.buttonClick.bind( this );
}

buttonClick() {
this.setState( { name : "Scott" } );
// Update State
}
}
State in Class Components
class Demo extends React.Component
{
.....
render() {
return <div>
<input type="text" value={this.state.uid}
onChange={this.handleUserIdChange} />

<input type="button" onClick={this.buttonClick}


value="Submit" />
</div>
}
}
Component Life Cycle
Hands-On Implementation
Narasimha
Sr. IT Trainer/Consultant
React Hooks

• Hooks are a new addition in React 16.8.


• They let you use state and other React features
without writing a class (using functional components).
• Hooks generally replace class components
• Hooks allow us to "hook" into React features such as
state and lifecycle methods.
• You must import Hooks from react.
React Hooks -- Rules

• Hooks are JavaScript functions, but they impose two


additional rules:
1. Only call Hooks at the top level. Don’t call Hooks inside
loops, conditions, or nested functions.
2. Only call Hooks from React function components. Don’t
call Hooks from regular JavaScript functions.
React Hooks – Important Hooks
1. useState
2. useParams
3. useNavigate
4. useRef
5. useEffect
6. useContext
useState
import {useState} from 'react’;
-------------------------------------------------------------------
let [count, setCount] = useState(0);
let [uid, setUid] = useState(“”);
--------------------------------------------------------------------
setCount(10);
setUid(“Scott”);
useParams

import { Link, useParams } from 'react-router-dom';

function Details(props)
{
const { id } = useParams();
…………………
}

export default Details;


useNavigate()

import { useNavigate } from "react-router-dom";


let navigate = useNavigate();
navigate("/Emps");
useRef

• useRef returns a mutable ref object.


• This objects refers the current dom element (object)
• ref object provides a property called "current" that
actually refers DOM object.
useRef
1. Create Reference Variable -- useRef()
const inputRef = useRef(null);

2. Apply Reference Variable -- ref attribute


<input ref={inputRef} type="text" />

3. Perform the operation using Reference variable


inputRef.current.focus();
useEffect
import {useEffect} from 'react’;

useEffect(callback, []);

useEffect(() =>
{
// code
}, []);
useEffect
useEffect(() =>{
let url =
"https://www.w3schools.com/angular/customers.php";
axios.get(url).then( (resData) => {
setCustomers(resData.data.records);

});

}, []);
useContext
1. Create contex
var contexObj = createContext(null);

2.
<contextObj.Provider value={userObj}>
// child
</contexObj.Provider>

3. Access the context


var obj = useContext(contextObj);
Hands-On Implementation

You might also like