Uif - Unit 2
Uif - Unit 2
02/20/2025 1
UNIT-II
REACTJS-PART-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.
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.
return (
<div>
<h1>React Event</h1>
<h3>This Example explains onlick event in React</h3>
<button onClick={alertBox}>Click Here</button>
</div>
);
}
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>
);
}
In React, Lists can be created in a similar way as we create lists in JavaScript.
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
return (
<div>
<h1>Lists and Keys in React</h1>
<h2>{output}</h2>
</div>
);
}
export default App
</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:
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
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():
this.userRef.current.value = “xyz”:
02/20/2025 UI Framework 21
Why we use Fragments?
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
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.
To use react routing, first, you need to install react-router-dom modules in your
application.
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
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>
)
}
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>
)
}
02/20/2025 UI Framework 40
Adding Bootstrap for React
Bootstrap can be added to the React app in several ways.
02/20/2025 UI Framework 41
1. Using the Bootstrap CDN
02/20/2025 UI Framework 42
2. Bootstrap as Dependency
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
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:
table {
border: 5px solid forestgreen;
width: 800px;
height: 200px;
}
th,td {
border: 1px solid rgb(19, 20, 19);
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
</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';
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:
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:
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>
</div>
);
}
}
ChildC component.
ChildA
React Context allows us to directly pass the data from the
a. Data
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.
return( return(
<div> <div>
<ChildB name =/> <ChildC/>
</div> </div>
); );
} }
export default ChildA; export default ChildB;
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
02/20/2025 UI Framework 86
Redux is a Predictable:
02/20/2025 UI Framework 87
React Redux
02/20/2025 UI Framework 88
use React Redux
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 Framework 93