VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
REACTJS.pdf
1. IT2304 – Full Stack Web Development Unit III- ReactJS
Prepared by Dr. R. Arthy, AP/IT 1
Department of Information Technology
2023 – 2024 (ODD SEMESTER)
Year : III IT Course Code : IT2304
Faculty
Name
: Dr. R. Arthy, AP/IT Course Name : Full Stack Web Development
Course code
(as per
NBA)
: 21ITC304 Regulation : R2021
UNIT III – USER INTERFACE CREATION USING REACT JS
Topic 1: Introduction
React is a declarative, efficient, and flexible JavaScript library for building user
interfaces
It is an open-source, component-based front end library responsible only for the view
layer of the application.
It was created by Jordan Walke, who was a software engineer at Facebook.
It was initially developed and maintained by Facebook and was later used in its
products like WhatsApp & Instagram. Facebook developed ReactJS in 2011 in its
newsfeed section, but it was released to the public in the month of May 2013.
Features
JSX
Components
One-way Data Binding
Virtual DOM
Simplicity
Performance
JSX
JSX stands for JavaScript XML. It is a JavaScript syntax extension.
It is an XML or HTML like syntax used by ReactJS.
This syntax is processed into JavaScript calls of React Framework.
2. IT2304 – Full Stack Web Development Unit III- ReactJS
Prepared by Dr. R. Arthy, AP/IT 2
Components
ReactJS is all about components.
ReactJS application is made up of multiple components, and each component has its
own logic and controls.
These components can be reusable which help you to maintain the code when
working on larger scale projects.
One-way Data Binding
ReactJS is designed in such a manner that follows unidirectional data flow or one-way
data binding.
The benefits of one-way data binding give you better control throughout the
application.
If the data flow is in another direction, then it requires additional features.
It is because components are supposed to be immutable and the data within them
cannot be changed. Flux is a pattern that helps to keep your data unidirectional.
This makes the application more flexible that leads to increase efficiency.
Virtual DOM
A virtual DOM object is a representation of the original DOM object.
It works like a one-way data binding.
Whenever any modifications happen in the web application, the entire UI is re-
rendered in virtual DOM representation.
Then it checks the difference between the previous DOM representation and new
DOM.
Once it has done, the real DOM will update only the things that have actually
changed. This makes the application faster, and there is no wastage of memory.
Simplicity
ReactJS uses JSX file which makes the application simple and to code as well as
understand.
Code reusability.
Performance
ReactJS is known to be a great performer.
This feature makes it much better than other frameworks out there today.
The reason behind this is that it manages a virtual DOM.
3. IT2304 – Full Stack Web Development Unit III- ReactJS
Prepared by Dr. R. Arthy, AP/IT 3
The DOM is a cross-platform and programming API which deals with HTML, XML
or XHTML.
The DOM exists entirely in memory.
Topic 2: Components
Components are independent and reusable bits of code.
They serve the same purpose as JavaScript functions, but work in isolation and return
HTML.
In ReactJS, we have mainly two types of components.
They are
o Functional Components
o Class Components
Functional Components
In React, function components are a way to write components that only contain a
render method and don't have their own state.
They are simply JavaScript functions that may or may not receive data as parameters.
Create a function that takes props(properties) as input and returns what should be
rendered.
Example 2
const root = ReactDOM.createRoot(document.getElementById('root'));
function Greeta() {
return <h1>This is the first React Application</h1>;
}
root.render(Greeta());
Example 3
function App() {
return (<h1>This is the first React Application.</h1>);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
Class Components
4. IT2304 – Full Stack Web Development Unit III- ReactJS
Prepared by Dr. R. Arthy, AP/IT 4
Class components are more complex than functional components.
Component and create a render function which returns a React element.
You can pass data from one class to other class components.
You can create a class by defining a class that extends Component and has a render
function.
class MyComponent extends React.Component {
render() {
return (
<div>This is main component.</div>
);
}
}
The class component is also known as a stateful component because they can hold or manage
local state.
Topic 3: JSX
JSX stands for JavaScript XML.
JSX allows us to write HTML in React.
JSX makes it easier to write and add HTML in React.
Features
o It is faster than regular JavaScript because it performs optimization while
translating the code to JavaScript.
o Instead of separating technologies by putting markup and logic in separate
files, React uses components that contain both.
o It is type-safe, and most of the errors can be found at compilation time.
o It makes easier to create templates.
Example:
const root = ReactDOM.createRoot(document.getElementById('root'));
const element = <h1>This is the first React Application</h1>;
root.render(element);
Expressions in JSX
With JSX you can write expressions inside curly braces { }.
5. IT2304 – Full Stack Web Development Unit III- ReactJS
Prepared by Dr. R. Arthy, AP/IT 5
The expression can be a React variable, or property, or any other valid JavaScript
expression.
const myElement = <h1>React is {5 + 5} times better with JSX</h1>;
Conditions - if statements
React supports if statements, but not inside JSX.
const x = 5;
let text = "Goodbye";
if (x < 10) {
text = "Hello";
}
const myElement = <h1>{text}</h1>;
Topic 4: State Management
Introduction
State management is one of the important and unavoidable features of any dynamic
application.
React provides a simple and flexible API to support state management in a React
component.
State represents the value of a dynamic properties of a React component at a given
instance.
React provides a dynamic data store for each component.
The internal data represents the state of a React component and can be accessed using
this.state member variable of the component.
Whenever the state of the component is changed, the component will re-render itself
by calling the render() method along with the new state.
Props
Props are arguments passed into React components.
Props are passed to components via HTML attributes.
Example 1
function App(props) {
return (<h1>This is the first React Application. This is {props.name}</h1>);
6. IT2304 – Full Stack Web Development Unit III- ReactJS
Prepared by Dr. R. Arthy, AP/IT 6
}
ReactDOM.createRoot(document.getElementById('root'));
root.render(<App name = "Dr.R.Arthy"/>);
useState()
The useState() is a Hook that allows you to have state variables in functional
components .
useState is the ability to encapsulate local state in a functional component.
Syntax:
The first element is the initial state and the second one is a function that is used for updating
the state.
const [state, setState] = useState(initialstate)
const [sum, setsum] = useState(function generateRandomInteger(){5+7);})
Importing:
To use useState you need to import useState from react as shown below:
import React, { useState } from "react"
Example 2
function Greet() {
const [username, setUsername] = useState('');
const [greeting, setGreeting] = useState('');
const handleUsernameChange = (event) => {
setUsername(event.target.value);
};
const handleGreet = () => {
if (username.trim() !== '') {
setGreeting(`Hello, ${username}!`);
}
7. IT2304 – Full Stack Web Development Unit III- ReactJS
Prepared by Dr. R. Arthy, AP/IT 7
};
return (
<div>
<h1>Greeting App</h1>
<div>
<input
type="text"
placeholder="Enter your username"
value={username}
onChange={handleUsernameChange}
/>
<button onClick={handleGreet}>Greet</button>
</div>
<p>{greeting}</p>
</div>
);
}
const root1 = ReactDOM.createRoot(document.getElementById('time'));
root1.render(<Greet />);
N Props State
1. Props are read-only. State changes can be asynchronous.
2. Props are immutable. State is mutable.
3. Props allow you to pass data from one component to
other components as an argument.
State holds information about the
components.
4. Props can be accessed by the child component. State cannot be accessed by child
components.
5. Props are used to communicate between components. States can be used for rendering dynamic
changes with the component.
6. Stateless component can have Props. Stateless components cannot have State.
7. Props make components reusable. State cannot make components reusable.
8. Props are external and controlled by whatever renders
the component.
The State is internal and controlled by the
React Component itself.
8. IT2304 – Full Stack Web Development Unit III- ReactJS
Prepared by Dr. R. Arthy, AP/IT 8
Topic 5: Event Handling
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.
General events
o Clicking an element
o Submitting a form
o Scrolling page
o Hovering an element
o Loading a webpage
o Input field change
o User stroking a key
o Image loading
Handling events with react have some syntactic differences from handling events on
DOM. These are:
o React events are named as camelCase instead of lowercase.
onClick instead of onclick.
o With JSX, a function is passed as the event handler instead of a string
onClick={shoot} instead of onClick="shoot()".
9. IT2304 – Full Stack Web Development Unit III- ReactJS
Prepared by Dr. R. Arthy, AP/IT 9
o In react, we cannot return false to prevent the default behavior. We must call
preventDefault event explicitly to prevent the default behavior.
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('You had clicked a Link.');
}
return (
<a href="#" onClick={handleClick}>
Click_Me
</a>
); }
Example:
function Greet() {
const [username, setUsername] = useState('');
const [greeting, setGreeting] = useState('');
const handleUsernameChange = (event) => {
setUsername(event.target.value);
};
const handleGreet = () => {
if (username.trim() !== '') {
setGreeting(`Hello, ${username}!`);
}
};
return (
<div>
<h1>Greeting App</h1>
<div>
<input
type="text"
10. IT2304 – Full Stack Web Development Unit III- ReactJS
Prepared by Dr. R. Arthy, AP/IT 10
placeholder="Enter your username"
value={username}
onChange={handleUsernameChange}
/>
<button onClick={handleGreet}>Greet</button>
</div>
<p>{greeting}</p>
</div>
);
}
const root1 = ReactDOM.createRoot(document.getElementById('time'));
root1.render(<Greet />);
Topic 6: Routing
Introduction
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.
React Router is used to define multiple routes in the application.
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.
React Router is a standard library system built on top of the React and used to create
routing in the React application using React Router Package.
It provides the synchronous URL on the browser with data that will be displayed on
the web page.
It maintains the standard structure and behavior of the application and mainly used for
developing single page web applications.
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.
11. IT2304 – Full Stack Web Development Unit III- ReactJS
Prepared by Dr. R. Arthy, AP/IT 11
Most of the social media websites like Facebook, Instagram uses React Router for
rendering multiple views.
React Router Installation
React contains three different packages for routing. These are:
o react-router: It provides the core routing components and functions for the
React Router applications.
o react-router-native: It is used for mobile applications.
o react-router-dom: It is used for web applications design.
Route
It is used to define and render component based on the specified path.
It will accept components and render to define what should be rendered.
Adding Navigation using Link component
When we click on any of that particular Link, it should load that page which is
associated with that path without reloading the web page.
To do this, we need to import <Link> component in the index.js file.
< Link> component
This component is used to create links which allow to navigate on different URLs and
render its content without reloading the webpage.
<NavLink> component
To add some styles to the Link.
Add properties activeStyle.
o The activeStyle properties specific style so that we can differentiate which one
is currently active.
<Link> vs <NavLink>
The Link component allows navigating the different routes on the websites, whereas
NavLink component is used to add styles to the active routes.
React Router Switch
The <Switch> component is used to render components only when the path will be
matched. Otherwise, it returns to the not found component.
React Router <Redirect>
A <Redirect> component is used to redirect to another route in our application to
maintain the old URLs.
It can be placed anywhere in the route hierarchy.
12. IT2304 – Full Stack Web Development Unit III- ReactJS
Prepared by Dr. R. Arthy, AP/IT 12
Nested Routing in React
Nested routing allows you to render sub-routes in your application.
<Route path="about" element={<About />}>
<Route path="services" element={<Services />}/>
<Route path="history" element={<History />}/>
<Route path="location" element={<Location />}/>
</Route>
Example:
import React from "react";
export function Home() {
return (
<div>
<h1>[Company Website]</h1>
</div>
);
}
export function About() {
return (
<div>
<h1>[About]</h1>
</div>
);
}
export function Contact() {
return (
<div>
<h1>[Contact]</h1>
</div>
);
}
import React from "react";
13. IT2304 – Full Stack Web Development Unit III- ReactJS
Prepared by Dr. R. Arthy, AP/IT 13
import { Routes, Route } from "react-router-dom";
import { Home, About, Contact } from "./pages";
function App() {
return (
<div>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />}/>
<Route path="/contact" element={<Contact />}/>
</Routes>
</div>
);}
import { Link } from "react-router-dom";
export function Home() {
return (
<div>
<h1>[Company Website]</h1>
<nav>
<Link to="about">About</Link>
<Link to="contact">Contact Us</Link>
</nav>
</div>
);
}
Topic 7: React Server
React Server is a powerful framework that allows you to build and manage server-
rendered React applications with ease.
It comes with built-in support for server-side state management, authentication, and
more.
React Server Components allows the server and the client (browser) to collaborate in
rendering your React application.
14. IT2304 – Full Stack Web Development Unit III- ReactJS
Prepared by Dr. R. Arthy, AP/IT 14
Before React Server Components, all React components are ―client‖ components —
they are all run in the browser.
When your browser visits a React page, it downloads the code for all the necessary
React components, constructs the React element tree, and renders it to the DOM (or
hydrates the DOM, if you’re using SSR).
The browser is a good place for this, because it allows your React application to be
interactive — you can install event handlers, keep track of state, mutate your React
tree in response to events, and update the DOM efficiently.
There are certain advantages that rendering on the server has over the browser:
o The server has more direct access to your data sources.
o The server can cheaply make use of ―heavy‖ code modules, like an npm
package for rendering markdown to html, because the server doesn’t need to
download these dependencies every time they’re used
Server components can focus on fetching data and rendering content, and client
components can focus on stateful interactivity, resulting in faster page loads, smaller
javascript bundle sizes, and a better user experience.
React server components is all about enabling this division of labor — let the server
do what it can do better upfront, before handing things off to the browser to finish the
rest.
Consider the React tree for your page, with some components to be rendered on the
server and some on the client.
15. IT2304 – Full Stack Web Development Unit III- ReactJS
Prepared by Dr. R. Arthy, AP/IT 15
Here’s one simplified way to think about the high-level strategy: the server can just
―render‖ the server components as usual, turning your React components into native
html elements like div and p.
But whenever it encounters a ―client‖ component meant to be rendered in the browser,
it just outputs a placeholder instead, with instructions to fill in this hole with the right
client component and props.
Then, the browser takes that output, fills in those holes with the client components,
and voila!
Example:
import ServerComponent from './ServerComponent.server'
export default function ClientComponent() {
return (
<div>
<ServerComponent />
</div>
)
}
export default function ClientComponent({ children }) {
return (
<div>
<h1>Hello from client land</h1>
16. IT2304 – Full Stack Web Development Unit III- ReactJS
Prepared by Dr. R. Arthy, AP/IT 16
{children}
</div>
)
}
// ServerComponent.server.jsx
export default function ServerComponent() {
return <span>Hello from server land</span>
}
import ClientComponent from './ClientComponent.client'
import ServerComponent from './ServerComponent.server'
export default function OuterServerComponent() {
return (
<ClientComponent>
<ServerComponent />
</ClientComponent>
)
}