0% found this document useful (0 votes)
23 views93 pages

Uif - Unit 2

The document outlines the syllabus and key concepts for a B.Tech course on UI Frameworks, specifically focusing on ReactJS. It covers topics such as React events, lists, keys, refs, fragments, and React Router, providing examples and explanations for each. The document also includes code snippets demonstrating the implementation of these concepts in React applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views93 pages

Uif - Unit 2

The document outlines the syllabus and key concepts for a B.Tech course on UI Frameworks, specifically focusing on ReactJS. It covers topics such as React events, lists, keys, refs, fragments, and React Router, providing examples and explanations for each. The document also includes code snippets demonstrating the implementation of these concepts in React applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 93

B.

Tech I-Year II-Sem


Subject: UI FRAMEWORKS
(MR24-1CS0105)

02/20/2025 1
UNIT-II

REACTJS-PART-II

02/20/2025 UI Web Development 2


Syllabus-UNIT II

React Events, React Lists, React Keys, React Refs, React Fragments,
React Router, React Styling using React Bootstrap, React Map, React
Table, Higher-Order Components, React Code Splitting, React Context,
React Hooks, React Redux.

02/20/2025 UI Web Development 3


React Events
An event is an action that could be triggered as a result of the user action or system
generated event. For example, a mouse click, loading of a web page, pressing a key,
window resizes, and other interactions are called events.

React has its own event handling system which is very similar to handling events on
DOM elements. The react event handling system is known as Synthetic Events. The
synthetic event is a cross-browser wrapper of the browser's native event.
React Events
Handling events with react have some syntactic differences from handling events on DOM.

These are:
1. React events are named as camelCase instead of lowercase.
(Eg.:onClick instead of onclick)
2. With JSX, a function is passed as the event handler instead of a string.

Event declaration in plain HTML:

<button onclick="showMessage()"> Hello MRU </button>

Event declaration in React:


 In Functional Component:<button onClick={showMessage}> Hello MRU </button>

 In Class Based Component: <button onClick={this.showMessage}>Hello MRU</button>


React Events-Example
import React from 'react';
function event() {
const alertBox = () => {
alert("Welcome to React Event !");
}

return (
<div>
<h1>React Event</h1>
<h3>This Example explains onlick event in React</h3>
<button onClick={alertBox}>Click Here</button>
</div>
);
}

export default event;

02/20/2025 UI Web Development 6


React Events
In react, we cannot return false to prevent the default behavior. We must
call preventDefault event explicitly to prevent the default behavior.
 For example: In plain HTML, to prevent the default link behavior of opening
a new page, we can write:
<a href="#" onclick="console.log('You had clicked a Link.'); return false"> Click_Me </a>

In React, we can write it as:

function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('You had clicked a Link.');
}
02/20/2025 UI Web Development 7
React Events- Prevent Default Link
import React from 'react';

function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('You had clicked a Link.');
}
return (
<div>
<h1> Prevent the default link behavior in React </h1>
<button type="button" onClick={handleClick}> Click_Me </button>
</div>
);
}

export default ActionLink;


02/20/2025 UI Web Development 8
React Lists
Lists are used to display data in an ordered format and mainly used to display menus on
websites.

In React, Lists can be created in a similar way as we create lists in JavaScript.

 The map() function is used for traversing the lists.


React Lists-Example 1
import React, { Component } from 'react';
class App extends Component{
render(){

const numbers = [1, 2, 3, 4, 5];


const listItems = numbers.map((n)=> <li>{n}</li> );
return (
<ul type="square">{listItems}</ul>
)
}
}
export default App;

02/20/2025 UI Web Development 10


React Lists-Example 2
import React, { Component } from 'react';
class App extends Component{
render(){
const listItems = ['Alpha', 'Beta','Gamma','Delta','Sigma','Omega' ];
const list = listItems.map((item) => <li>{item}</li>);
return (
<div>
<h1>Creating an Ordered list</h1>
<h2>The list items are displayed below </h2>
<ol type="i">{list}</ol>
</div>
)
}
}
export default App;

02/20/2025 UI Web Development 11


React Keys
A “key” is a special string attribute you need to include when creating lists of elements in
React.

Keys allow React to keep track of elements. This way, if an item is updated or removed, only
that item will be re-rendered instead of the entire list.

Generally, the key should be a unique ID assigned to each item. As a last resort, you can use
the array index as a key.

Keys help React identify which items have changed, are added, or are removed. Keys should
be given to the elements inside the array to give the elements a stable identity
Importance of Keys

import React from "react";


function App() {
const langs = [ "HTML", "CSS", "JS"]
const output=langs.map((l) =>
<li>{l}</li>)

return (
<div>
<h1>Lists and Keys in React</h1>
<h2>{output}</h2>

</div>
);
}
export default App

02/20/2025 UI Web Development 13


Importance of Keys
The warning can be eliminated by inserting key={index} in the map
function as follows
import React from "react";
function App() {
const langs = [ "HTML", "CSS",
"JS"]
const output=langs.map((l,index)
=> <li key={index}>{l}</li>)
WARNING ELIMINATED
return (
<div>
<h1>Lists and Keys in
React</h1>
<h2>{output}</h2>

</div>
);
02/20/2025 UI Web Development 14
Note:
 It is not recommended to use indexes for keys if the order of the item may change in future. It creates
confusion for the developer and may cause issues with the component state.
 Hence, instead of index each element of the array can be given an unique id as follows:

import React from "react";


function App() {
const langs = [{id:1, lang :"HTML"} ,
{id:2, lang:"CSS"},
{id:3, lang:"JS"}
]
const output=langs.map((l) => <li key={l.id} > {l.lang} </li>)

return (
<div>
<h1>Lists and Keys in React</h1>
<h2>{output}</h2>
</div>
);
}
export default App
02/20/2025 UI Framework 15
EXAMPLE 2
import React, { useState } from 'react'; return (
<div>
const App = () => { <h1>Items List</h1>
const [items, setItems] = useState([ <ul>
{ id: 1, name: 'Item 1' }, {items.map(item => (
{ id: 2, name: 'Item 2' }, <li key={item.id}>
{ id: 3, name: 'Item 3' }, {item.name}
]); <button onClick={() =>
removeItem(item.id)}>Remove</button>
const removeItem = (id) => { </li>
setItems(items.filter(item => item.id !== id)); ))}
}; </ul>
</div>
);
};
By clicking remove button
Each item get removed export default App;

02/20/2025 UI Framework 16
React Refs

• Refs is the shorthand used for references in React.


• It is an attribute which makes it possible to store a reference to
particular DOM nodes or React elements.
• It provides a way to access React DOM nodes or React elements and
how to interact with it.
• It is used when we want to change the value of a child component,
without making the use of props.

02/20/2025 UI Framework 17
When to Use Refs?
Refs can be used in the following cases:
• When we need DOM measurements such as managing focus, text
selection, or media playback.
• It is used in triggering imperative animations.
• When integrating with third-party DOM libraries.
• It can also use as in callbacks.
How to create Refs
In React, Refs can be created by using React.createRef().

02/20/2025 UI Framework 18
Refs - Example
import React, {Component} from 'react';
class App extends Component {
constructor (){
super()
this.userRef=React.createRef();
}
editVal()
{
this.userRef.current.focus()
this.userRef.current.value = "xyz"
}
render(){
return(
<div>
<h1>Ref in React</h1>
<input ref={this.userRef} type="text" name="user"></input>
<button onClick={() => this.editVal()}>ClickMe</button>
</div>
);
}
} export default App
02/20/2025 UI Web Development 19
this.userRef.current.focus():

Manages focus for the current input text box

this.userRef.current.value = “xyz”:

Assigns value to the current input text box

02/20/2025 UI Web Development 20


React Fragments

• In React, whenever you want to render something on the


screen, you need to use a render method inside the component.
• This render method can return single elements
or multiple elements.
• However, if you want to return multiple elements, the render
method will require a 'div' tag and put the entire content or
elements inside it.
• This extra node to the DOM sometimes results in the wrong
formatting of your HTML output.

02/20/2025 UI Framework 21
Why we use Fragments?

The main reason to use Fragments tag is:


• It makes the execution of code faster as compared to the div tag.
• It takes less memory.

02/20/2025 UI Framework 22
Fragments - Example
import React from 'react';

function box () {
alert("Hi Welcome")
}
function frag(){
return (
<React.Fragment>
<h1>Hello</h1>
<p>This is an example of a
fragment.</p>
<button onClick= {box}>Click
me</button>

</React.Fragment>

);
} 02/20/2025 UI Web Development 23
export default frag;
React Router

React Router is a powerful routing library built on top of


React that helps you add new screens and flows to your
application incredibly quickly, all while keeping the URL in
sync with what's being displayed on the page.
Routing is a process in which a user is directed to different
pages based on their action or request. ReactJS Router is
mainly used for developing Single Page Web Applications.
When a user types a specific URL into the browser, and if
this URL path matches any 'route' inside the router file, the
user will be redirected to that particular route.
02/20/2025 UI Framework 24
Need of React Router:

• React Router plays an important role to display multiple views in a


single page application. Without React Router, it is not possible to
display multiple views in React applications.

• Most of the social media websites like Facebook, Instagram uses


React Router for rendering multiple views.

02/20/2025 UI Framework 25
React Router Installation
React contains three different packages for routing. These are:

1. react-router: It provides the core routing components and functions for the
React Router applications.
2. react-router-native: It is used for mobile applications.
3. react-router-dom: It is used for web applications design.

02/20/2025 UI Web Development 26


React Router Installation
It is not possible to install react-router directly in your application.

To use react routing, first, you need to install react-router-dom modules in your
application.

 The below command is used to install react router dom.

$ npm install react-router-dom --save

02/20/2025 UI Web Development 27


Components in React Router
There are two types of router components:

<BrowserRouter>: It is used for handling the dynamic URL.

<HashRouter>: It is used for handling the static request.

02/20/2025 UI Web Development 28


Step 1:npm install react-router-dom in terminal

02/20/2025 UI Framework 29
Check:React
router is installed
In depecdencis-
package.json

02/20/2025 UI Framework 30
Index.js file-already existing file in the react

import React from 'react';


import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

02/20/2025 UI Framework 31
In Index.js file include
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals’;
import { BrowserRouter } from "react-
router-dom";
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(
< BrowserRouter >
<App />
</ BrowserRouter >
);
02/20/2025 UI Framework 32
APP.js
import { Routes, Route } from "react-router-dom"
import Home from "./home"
import About from "./about"
import Contact from "./contact"
import Nav from "./nav"

function App() {
return (
<div>
<h1><center>MALLA REDDY UNIVERSITY</center></h1>
<Nav/>
<Routes>
<Route path=“home" element={ <Home/> } />
<Route path="about" element={ <About/> } />
<Route path="contact" element={ <Contact/> } />
</Routes>
</div>
)
}

export default App


02/20/2025 UI Framework 33
about.js
import React from 'react'
function about() {
return (
<div>
<h2>Malla Reddy University, Hyderabad (As per Telangana State
Private Universities Act No. 13 of 2020, Higher Education (UE)
Department dt. 15.6.2020) was established in the year 2020 through the
State Legislature Council of Telangana, Govt. of Telangana. It is
offering industry-focused specialised Undergraduate and Postgraduate
courses with the aim of providing Quality Higher Education on par with
International standards. It persistently seeks and adopts innovative
methods to improve the quality of higher education on a consistent basis.
</h2>
</div>
)
}

export default about


02/20/2025 UI Framework 34
home.js
import React from 'react'
function Home() {
return (
<div>
<h1>PROGRAMMES OFFERED</h1>
<h2> <li>School ofEngineering</li>
<li>School of Agricultural Sciences</li>
<li>School of Allied Healthcare Sciences</li>
<li>School of Management</li>
<li>School of Sciences</li>
<li>School of Commerce & Arts</li>
</h2>
</div>
);
}
export default Home;

02/20/2025 UI Framework 35
contact.js
import React from 'react'
function Contact() {
return (
<div>
<h1>Maisammaguda, Dulapally,
Hyderabad, Telangana 500100<br></br>
Phone: 94971-94971, 91778-78365<br></br>
info@mallareddyuniversity.ac.in<br></br>
admissions@mallareddyuniversity.ac.in</
h1>
</div>
)
}

export default Contact


02/20/2025 UI Framework 36
nav.js
import { Link } from 'react-router-dom'
const Nav = () => {
return(
<nav>
<ul>
<li><Link to="/home">Home</Link></li>
<li><Link
to="/about">About</Link></li>
<li><Link
to="/contact">Contact</Link></li>
</ul>
</nav>
)
}

export default Nav;


02/20/2025 UI Framework 37
02/20/2025 UI Web Development 38
02/20/2025 UI Web Development 39
React Styling using React Bootstrap

• React-Bootstrap is a front-end UI component library built with


React. It is used to build responsive, mobile-first projects on the web.
• React-Bootstrap provides a wide range of components, including
buttons, navbars, tabs, cards, and modals.
• It also provides a number of layout components, such as grids and
containers.
• React-Bootstrap is easy to use and well-documented. It is a popular
choice for building React applications, and it is used by companies
like Facebook, Twitter, and Airbnb.

02/20/2025 UI Framework 40
Adding Bootstrap for React
Bootstrap can be added to the React app in several ways.

The three most common ways are given below:

1. Using the Bootstrap CDN


2. Bootstrap as Dependency
3. React Bootstrap Package

02/20/2025 UI Framework 41
1. Using the Bootstrap CDN

• There is no need to install or download Bootstrap.


• We can simply put an <link> into the <head> section of
the index.html file of the React app as shown in the following snippet.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/


bootstrap.min.css" integrity="sha384ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/
iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

02/20/2025 UI Framework 42
2. Bootstrap as Dependency

• If we are using a build tool or a module bundler such as Webpack,


then importing Bootstrap as dependency is the preferred option for
adding Bootstrap to the React application.
• We can install Bootstrap as a dependency for the React app.
• To install the Bootstrap, run the following commands in the terminal
window.
npm install bootstrap

02/20/2025 UI Framework 43
3.React Bootstrap Package
The two most popular Bootstrap packages are:
1.react-bootstrap:
• It is a complete re-implementation of the Bootstrap components as
React components.
• It does not need any dependencies like bootstrap.js or jQuery.
• If the React setup and React-Bootstrap installed, we have everything
which we need.

02/20/2025 UI Framework 44
2.reactstrap:
• It is a library which contains React Bootstrap 4 components that favor
composition and control.
• It does not depend on jQuery or Bootstrap JavaScript.
• However, react-popper is needed for advanced positioning of content
such as Tooltips, Popovers, and auto-flipping Dropdowns.

02/20/2025 UI Framework 45
Installation

After creating the React app, the best way to install Bootstrap is via the
npm package. To install Bootstrap, navigate to the React app folder,
(c:/Users/MRUH/myfolder/myapp>)and run the following command.
npm install react-bootstrap

02/20/2025 UI Framework 46
In package.json bootstrap module is installed

Now, React
Bootstrap is
successfully
installed in our
project.

02/20/2025 UI Framework 47
Adding Stylesheets
• The React Bootstrap component does not contain styles to provide
them; we have to add the bootstrap stylesheets to our application.
• To add the stylesheets, import them into your app.js or index.js file.
To import the CSS file, include the following line in the import section
(top) of the file:
import 'bootstrap/dist/css/
bootstrap.min.css';

02/20/2025 UI Framework 48
Example- Bootstrap
import 'bootstrap/dist/css/bootstrap.min.css';
import {Button} from 'react-bootstrap'
var myStyle = {
textAlign:'center',
fontFamily: 'Courier',
}

function App() {
return (
<div className="App" style={myStyle}>
<h1>MALLA REDDY UNIVERSITY</h1>
<Button className='m-5' variant="primary">HOME</Button>
<Button className='m-5' variant="secondary">ABOUT US</Button>
<Button className='m-5' variant="success">CONTACT</Button>
<Button className='m-5' variant="danger">GALLARY</Button>
<Button className='m-5' variant="primary">NEWS</Button>
</div>
);
}
export default App;
02/20/2025 UI Framework 49
Example- Bootstrap-OUTPUT

02/20/2025 UI Web Development 50


React Map
 A map is a data collection type where data is stored in the form of pairs.
 It contains a unique key. The value stored in the map must be mapped to the key.
 We cannot store a duplicate pair in the map(). It is because of the uniqueness of each stored
key. It is mainly used for fast searching and looking up data.

 The map() method creates a new array by calling a provided function on every element in the
calling array.
Example:
In React, the map method is used to : var numbers = [1, 2, 3, 4, 5];
const doubleValue = numbers.map((number)=>{
1. Traversing the list element. return (number * 2);
2. Traversing the list element with keys. });
console.log(doubleValue);
02/20/2025 UI Web Development 51
React Table
A table is an arrangement which organizes information into rows and columns.
It is used to store and display data in a structured format.
Features:
1. It is lightweight at 11kb (and only need 2kb more for styles).
2. It is fully customizable (JSX, templates, state, styles, callbacks).
3. It is fully controllable via optional props and callbacks.
4. It has client-side & Server-side pagination.
5. It has filters.
6. Pivoting & Aggregation
7. 02/20/2025
Minimal design & easily themeable UI Web Development 52
React Table
React Table (now TanStack Table) is a popular open-source library for building tables and
datagrids in React applications. It provides a flexible and performant foundation for creating
interactive and visually appealing tables with features like:
Core Functionalities:
• Sorting: Allows users to sort data by clicking on column headers.
• Filtering: Enables users to search and filter data based on specific criteria.
• Pagination: Facilitates managing large datasets by displaying data in smaller, manageable
portions with navigation for browsing through pages.
Additional Capabilities:
Virtualization: Enhances performance by rendering only visible rows, improving scrolling
experience for large datasets.
Customizable: Offers flexibility to tailor the table's appearance and behavior to your specific
needs through hooks and options.
Headless: Does not enforce a specific UI or styles, allowing you to control the look and feel of
the table through custom CSS or design systems.
02/20/2025 UI Web Development 53
React Table- Installation
Step 1:
Type the following command in the Terminal:
c:\Users\SOE-III\myfolder\myapp> npm install react-table

Step 2: import the react-table into the react component. To do this, add the
following statement to the App.js file:

import ReactTable from "react-table";


02/20/2025 UI Web Development 54
React Table- Example
App.js File
import React from 'react';
import './App.css' <tr>
<td>Megha</td>
function App() { <td>19</td>
return ( <td>Female</td>
<div > </tr>
<h1>Table using <tr>
React</h1> <td>Subham</td>
<table> <td>25</td>
<tr> <td>Male</td>
<th>Name</th> </tr>
<th>Age</th> </table>
<th>Gender</th> </div>
</tr> );
<tr> }
<td>Anish</td>
<td>19</td> export default App;
02/20/2025 UI Web Development 55
<td>Male</td>
React Table- Example
App.css File

table {
border: 5px solid forestgreen;
width: 800px;
height: 200px;
}

th,td {
border: 1px solid rgb(19, 20, 19);

02/20/2025 UI Web Development 56


React Higher-Order Components (HOC)
 It is also known as HOC. In React, HOC is an advanced technique for reusing component
logic.
 It is a component that takes another component as input and returns a new
component with extra features added to the original component.
 A higher order component function accepts another function as an argument.
 The main goal of this is to decompose the component logic into simpler and smaller
functions that can be reused as you need.

02/20/2025 UI Web Development 57


React Higher-Order Components (HOC)-Example
A function is said to be Higher Order function High(example) {
Component if: return (props) => {
Return <example {… props}/>
 Case 1: If another function is called into this }
function or }
 Case-2: If another function is returned from Case1 eg.: Function example is called into the function
this function High. Therefore, High is called HOC

function App() {
Example: return (
function example(props) { <p>example name =“John”</p>
return ( )}
<p> Hello {props.name} </p> Case2 eg.: Function example is returned
)} from App function. Hence, App is HOC

02/20/2025 UI Web Development 58


Example-HOC
//Function Creation
function add (a, b) {
return a + b
}
function higherOrder(a, addReference) {
return addReference(a, 20)
}
//Function call
higherOrder(30, add) // 50
02/20/2025 UI Web Development 59
import React from 'react';
function AuthCheck(Comp) { function Login() {
let authenticated=true; return(
return(abc) => { <h1> This is Login Component </h1>
if(authenticated) {
return <Comp {...abc} /> )
} }
else {
return <Login/> const AuthChecked = AuthCheck(User)
}
} function App(){
} return (
<AuthChecked username={"John"}/>
function User(x) { )
return( }
<div>
<h1> This is User Component</h1> export default App;
<h2> Hello {x.username}</h2>
</div>
);
}

02/20/2025 UI Web Development 60


React Higher-Order Components (HOC)-Example
HOC.js File

import React, {Component} from 'react';

function Hoc (HocComponent){


return class extends Component{
render(){
return (
<div>
<HocComponent/>

</div>

);
}
}
} 02/20/2025
export default Hoc UI Web Development 61
React Higher-Order Components (HOC)-Example
App.js File
import React, { Component } from 'react';
import HOC from './HOC';

class App extends Component {


render() {
return (
<div>
<h2>HOC Example</h2>
<h3>HOC is a component that takes another component as input and
returns a new component with extra features added to the original
component</h3>
</div>
)
}
}
App = 02/20/2025
HOC(App); UI Web Development 62
React Code Splitting
The React app bundles their files using tools like Webpack or Browserfy.
Bundling is a process in which multiple files are merged into a single file,
which is called a bundle.
The bundle is responsible for loading an entire app at once on the webpage.
Code-Splitting is a feature supported by Webpack and Browserify, which can
create multiple bundles that can be dynamically loaded at runtime.

Code splitting uses React.lazy and Suspense tool/library, which helps to


load a dependency lazily and only load it when needed by the user.

02/20/2025 UI Web Development 63


Why Do We Need Code Splitting?
When building large-scale applications, the JavaScript bundle can become
quite large, which can impact the load time of the application.
Code splitting is a technique where we split our code into various bundles
which can then be loaded on demand or in parallel.
This can significantly reduce the load time of our application.

02/20/2025 UI Web Development 64


React.lazy
React.lazy is a function that lets you render a dynamic import as a regular
react component.
It makes it possible to load components lazily, which can be very useful for
reducing the size of the initial JavaScript bundle that the user's browser has to
download and parse.
Without using React.lazy function:

import ExampleComponent from './ExampleComponent';

Using React.lazy function:

const ExampleComponent = React.lazy(() => import('./ExampleComponent'));

02/20/2025 UI Web Development 65


<suspense>
 the <suspense> component is responsible for handling the
output when the lazy component is fetched and rendered.

const ExampleComponent = React.lazy(() => import('./ ExampleComponent'));

function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<ExampleComponent />
</Suspense> NOTE:
</div>  The fallback prop accepts the React elements which
); you want to render while waiting for the component
} to load.
 We can combine multiple lazy components with a
single Suspense component.
02/20/2025 UI Web Development 66
Example-Code Splitting
about.js file:

import React from 'react'

function about() {
return (
<div>
<h2>Malla Reddy University, Hyderabad (As per Telangana State Private
Universities Act No. 13 of 2020, Higher Education (UE) Department dt.
15.6.2020) was established in the year 2020 through the State Legislature Council
of Telangana, Govt. of Telangana. It is offering industry-focused specialised
Undergraduate and Postgraduate courses with the aim of providing Quality Higher
Education on par with International standards. It persistently seeks and adopts
innovative methods to improve the quality of higher education on a consistent
basis. </h2>
</div>
)
}
export default about
02/20/2025 UI Web Development 67
Example-Code Splitting
home.js file:

import React from 'react'

function Home() {
return (
<div>
<h1>PROGRAMMES OFFERED</h1>
<h2> <li>School ofEngineering</li>
<li>School of Agricultural Sciences</li>
<li>School of Allied Healthcare Sciences</li>
<li>School of Management</li>
<li>School of Sciences</li>
<li>School of Commerce & Arts</li>
</h2>
</div>
);
}
export default Home;
02/20/2025 UI Web Development 68
Example-Code Splitting
check.js file:
import React, {useState, lazy, Suspense} from 'react';
const About=lazy(() => import('./about'));
const Home=lazy(() => import('./home'));
function Selection() {
const [selectedTab,setSelectedTab] = useState('');
return(
<div>
<div>

<button onClick={ () => setSelectedTab ('homeTab')}> Home</button>


<button onClick={ () => setSelectedTab ('aboutTab')}> About</button>
</div>
<Suspense fallback={<div> Loading....</div>}>
{selectedTab === 'homeTab' && <Home/>}
{selectedTab === 'aboutTab' && <About/>}
</Suspense>
</div>
)
} export default Selection;
02/20/2025 UI Web Development 69
Example-Code Splitting
app.js file:

import React, {Component} from 'react';


import Selection from './check.js';

class App extends Component {


render (){
return (
<div>
< Selection />

</div>

);
}
}

export default App;

02/20/2025 UI Web Development 70


OUTPUT:

02/20/2025 UI Web Development 71


Only these 5 files are rendered before the buttons are pressed
02/20/2025 UI Web Development 72
When the user clicks on Home Button, home.js file is added to the existing list
02/20/2025 UI Web Development 73
02/20/2025 UI Web Development 74
Now, when the user clicks on the about button, about.js file is rendered.
React Context
Context allows passing data through the component tree without passing
props down manually at every level.

Context provides a way to pass values between components without


explicitly passing a prop through every level of the component tree.

How to use Context ?


There are two main steps to use the React context into the React application:
 Setup a context provider and define the data which you want to store.
 Use a context consumer whenever you need the data from the store

02/20/2025 UI Web Development 75


React Context
 To pass the data from parent component to ChildC component ,
Parent
first its has to be passed to ChildA then to ChildB and then to

ChildC component.
ChildA
 React Context allows us to directly pass the data from the

parent component any child component directly.


ChildB  For this, we need to have the following:

a. Data

ChildC b. Provider (component which will pass the data)

c. Consumer (component which will receive the data)

02/20/2025 UI Web Development 76


React Context – Example without using Context
App.js File: childA.js File:

import React from 'react';


import React from 'react'; import ChildB from './childB';
import ChildA from './childA'; function ChildA({name}){
function App(){
const name = "MRUH" return(
return( <div>
<div> <ChildB name
<ChildA name ={name}/>
={name}/> </div>
</div> );
); }
} export default ChildA;
export default App;

02/20/2025 UI Web Development 77


React Context – Example without using Context
childB.js File: childC.js File:

import React from 'react';


import React from 'react';
import ChildC from './childC'; function ChildC({name}){
function ChildB({name}){
return(
return( <div>
<div> <h1>Malla Reddy
<ChildC name University {name}</h1>
={name}/> </div>
</div> );
); }
} export default ChildC;
export default ChildB;

02/20/2025 UI Web Development 78


NOTE:

In the previous example the data with variable “name” is passed from
the parent component i.e., App.js file to childA  childB  childC.

But, with the use of React Context we can pass the data directly from
App.js component to childC.js component.

02/20/2025 UI Web Development 79


React Context – Example using Context

Modified childB.js File:


Modified childA.js File:

import React from 'react'; import React from 'react';


import ChildB from './childB'; import ChildC from './childC';
function ChildA(){ function ChildB(){

return( return(
<div> <div>
<ChildB name =/> <ChildC/>
</div> </div>
); );
} }
export default ChildA; export default ChildB;

02/20/2025 UI Web Development 80


React Context – Example- using Context
Modified App.js File: Modified childC.js File:

import React, {createContext} from import React from 'react';


'react'; import {data} from './App'
import ChildA from './childA'; function ChildC(){
const data = createContext();
return(
function App(){ <div>
const name = "MRUH" <data.Consumer>
return( {
<div> (name) => {
<data.Provider value return(
={name}> <h1>My University name is
<ChildA/> {name}</h1>
</data.Provider> )
</div> }
); }
}
export default App; </data.Consumer>
export {data};
</div>
02/20/2025 UI Web Development 81
);
React Hooks
Hooks are the new feature introduced in the React 16.8 version.
It allows you to use state and other React features without writing a class.
It does not work inside classes.
When to use Hooks?
 If you write a function component, and then you want to add some state to it,
previously you do this by converting it to a class.
 But, now you can do it by using a Hook inside the existing function component.

02/20/2025 UI Web Development 82


Rules of Hooks
1. Only call Hooks at the top level:
Do not call Hooks inside loops, conditions, or nested functions. Hooks should
always be used at the top level of the React functions. This rule ensures that Hooks
are called in the same order each time a components renders.

2. Only call Hooks from React functions:


You cannot call Hooks from regular JavaScript functions. Instead, you can call
Hooks from React function components. Hooks can also be called from custom
Hooks.
Pre-requisites for React Hooks:
1. Node version 6 or above
2. NPM version 5.2 or above
3. Create-react-app tool for running the React App
02/20/2025 UI Web Development 83
Hooks Example
import React, { useState } from 'react';

function CountApp() {
// Declare a new state variable, which we'll call
"count"
const [count, setCount] = useState(0);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default CountApp;
02/20/2025 UI Web Development 84
React Redux

 It is a state management library


 Redux is not tied to React.
 It can be used with React, Angular, Vue etc.
 It is a library for Javascript applications

Redux is a State Container:


 Redux stores the state of your Application(App)
 State of an App is the state represented by all the individual
components of that App
e.g: state ={
username : ‘1’}
02/20/2025 UI Framework 85
Redux is a State Container:

 Redux stores the state of your Application(APP)


 State of an APP is the state represented by all the individual
components of that APP
e.g: state ={
username : ‘1’,
password : ‘*****’
submitted: ‘false’
}
Redux will store and manage the APP state

02/20/2025 UI Framework 86
Redux is a Predictable:

 Redux is a predictable state container for Javascript Apps

React React-Redux Redux

 React and Redux works independently of each other


 To directly use redux in React is bit confusing and difficult, hence we
use React-Redux package in between React and Redux.

02/20/2025 UI Framework 87
React Redux

• Redux is an open-source JavaScript library used to manage application


state. React uses Redux for building the user interface.
• React Redux is the official React binding for Redux. It allows React
components to read data from a Redux Store, and dispatch Actions to
the Store to update data.
• Redux helps apps to scale by providing a sensible way to manage state
through a unidirectional data flow model. React Redux is conceptually
simple.
• It subscribes to the Redux store, checks to see if the data which your
component wants have changed, and re-renders your component.

02/20/2025 UI Framework 88
use React Redux

• React Redux is the official UI bindings for react Application. It is


kept up-to-date with any API changes to ensure that your React
components behave as expected.
• It encourages good 'React' architecture.
• It implements many performance optimizations internally, which
allows to components re-render only when it actually needs.

02/20/2025 UI Framework 89
Redux Architecture

02/20/2025 UI Framework 90
The components of Redux architecture are explained below.
STORE: A Store is a place where the entire state of your application lists. It manages the
status of the application and has a dispatch(action) function. It is like a brain responsible
for all moving parts in Redux.
ACTION: Action is sent or dispatched from the view which are payloads that can be
read by Reducers. It is a pure object created to store the information of the user's event. It
includes information such as type of action, time of occurrence, location of occurrence,
its coordinates, and which state it aims to change.
REDUCER: Reducer read the payloads from the actions and then updates the store via
the state accordingly. It is a pure function to return a new state from the initial state.
02/20/2025 UI Framework 91
What are the core principles of Redux?
Redux follows three fundamental principles:
Single source of truth: The state of your whole application is stored in an
object tree within a single store. The single state tree makes it easier to keep
track of changes over time and debug or inspect the application.
State is read-only: The only way to change the state is to emit an action, an
object describing what happened. This ensures that neither the views nor the
network callbacks will ever write directly to the state.
Changes are made with pure functions: To specify how the state tree is
transformed by actions, you write reducers. Reducers are just pure functions
that take the previous state and an action as parameters, and return the next
state.

02/20/2025 UI Web Development 92


THANK YOU

02/20/2025 UI Framework 93

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy