SlideShare a Scribd company logo
1 of 16
Download to read offline
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.
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.
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
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 { }.
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>);
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}!`);
}
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.
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()".
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"
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.
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.
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";
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.
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.
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>
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>
)
}

More Related Content

Similar to REACTJS.pdf

React Interview Questions and Answers by Scholarhat
React Interview Questions and Answers by ScholarhatReact Interview Questions and Answers by Scholarhat
React Interview Questions and Answers by ScholarhatScholarhat
 
All about React Js
All about React JsAll about React Js
All about React JsGargi Raghav
 
Top 20 ReactJS Interview Questions and Answers in 2023.pdf
Top 20 ReactJS Interview Questions and Answers in 2023.pdfTop 20 ReactJS Interview Questions and Answers in 2023.pdf
Top 20 ReactJS Interview Questions and Answers in 2023.pdfAnanthReddy38
 
FRONTEND DEVELOPMENT WITH REACT.JS
FRONTEND DEVELOPMENT WITH REACT.JSFRONTEND DEVELOPMENT WITH REACT.JS
FRONTEND DEVELOPMENT WITH REACT.JSIRJET Journal
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥Remo Jansen
 
Unit 2 Fundamentals of React -------.pptx
Unit 2 Fundamentals of React -------.pptxUnit 2 Fundamentals of React -------.pptx
Unit 2 Fundamentals of React -------.pptxkrishitajariwala72
 
React Interview Question & Answers PDF By ScholarHat
React Interview Question & Answers PDF By ScholarHatReact Interview Question & Answers PDF By ScholarHat
React Interview Question & Answers PDF By ScholarHatScholarhat
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)Chiew Carol
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Previewvaluebound
 
What are the components in React?
What are the components in React?What are the components in React?
What are the components in React?BOSC Tech Labs
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js SimplifiedSunil Yadav
 

Similar to REACTJS.pdf (20)

reactJS
reactJSreactJS
reactJS
 
React Interview Questions and Answers by Scholarhat
React Interview Questions and Answers by ScholarhatReact Interview Questions and Answers by Scholarhat
React Interview Questions and Answers by Scholarhat
 
Presentation1
Presentation1Presentation1
Presentation1
 
All about React Js
All about React JsAll about React Js
All about React Js
 
ReactJs
ReactJsReactJs
ReactJs
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
 
React
ReactReact
React
 
SharePoint Framework y React
SharePoint Framework y ReactSharePoint Framework y React
SharePoint Framework y React
 
Top 20 ReactJS Interview Questions and Answers in 2023.pdf
Top 20 ReactJS Interview Questions and Answers in 2023.pdfTop 20 ReactJS Interview Questions and Answers in 2023.pdf
Top 20 ReactJS Interview Questions and Answers in 2023.pdf
 
ReactJS (1)
ReactJS (1)ReactJS (1)
ReactJS (1)
 
FRONTEND DEVELOPMENT WITH REACT.JS
FRONTEND DEVELOPMENT WITH REACT.JSFRONTEND DEVELOPMENT WITH REACT.JS
FRONTEND DEVELOPMENT WITH REACT.JS
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
 
Unit 2 Fundamentals of React -------.pptx
Unit 2 Fundamentals of React -------.pptxUnit 2 Fundamentals of React -------.pptx
Unit 2 Fundamentals of React -------.pptx
 
React Interview Question & Answers PDF By ScholarHat
React Interview Question & Answers PDF By ScholarHatReact Interview Question & Answers PDF By ScholarHat
React Interview Question & Answers PDF By ScholarHat
 
React
ReactReact
React
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
What are the components in React?
What are the components in React?What are the components in React?
What are the components in React?
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js Simplified
 
react-slides.pptx
react-slides.pptxreact-slides.pptx
react-slides.pptx
 

More from ArthyR3

Unit IV Knowledge and Hybrid Recommendation System.pdf
Unit IV Knowledge and Hybrid Recommendation System.pdfUnit IV Knowledge and Hybrid Recommendation System.pdf
Unit IV Knowledge and Hybrid Recommendation System.pdfArthyR3
 
VIT336 – Recommender System - Unit 3.pdf
VIT336 – Recommender System - Unit 3.pdfVIT336 – Recommender System - Unit 3.pdf
VIT336 – Recommender System - Unit 3.pdfArthyR3
 
OOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfOOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfArthyR3
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfArthyR3
 
MongoDB.pdf
MongoDB.pdfMongoDB.pdf
MongoDB.pdfArthyR3
 
ANGULARJS.pdf
ANGULARJS.pdfANGULARJS.pdf
ANGULARJS.pdfArthyR3
 
JQUERY.pdf
JQUERY.pdfJQUERY.pdf
JQUERY.pdfArthyR3
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301ArthyR3
 
CNS - Unit v
CNS - Unit vCNS - Unit v
CNS - Unit vArthyR3
 
Cs8792 cns - unit v
Cs8792   cns - unit vCs8792   cns - unit v
Cs8792 cns - unit vArthyR3
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit ivArthyR3
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit ivArthyR3
 
Cs8792 cns - unit i
Cs8792   cns - unit iCs8792   cns - unit i
Cs8792 cns - unit iArthyR3
 
Java quick reference
Java quick referenceJava quick reference
Java quick referenceArthyR3
 
Cs8792 cns - Public key cryptosystem (Unit III)
Cs8792   cns - Public key cryptosystem (Unit III)Cs8792   cns - Public key cryptosystem (Unit III)
Cs8792 cns - Public key cryptosystem (Unit III)ArthyR3
 
Cryptography Workbook
Cryptography WorkbookCryptography Workbook
Cryptography WorkbookArthyR3
 
Cs6701 cryptography and network security
Cs6701 cryptography and network securityCs6701 cryptography and network security
Cs6701 cryptography and network securityArthyR3
 
Compiler question bank
Compiler question bankCompiler question bank
Compiler question bankArthyR3
 
Compiler gate question key
Compiler gate question keyCompiler gate question key
Compiler gate question keyArthyR3
 

More from ArthyR3 (20)

Unit IV Knowledge and Hybrid Recommendation System.pdf
Unit IV Knowledge and Hybrid Recommendation System.pdfUnit IV Knowledge and Hybrid Recommendation System.pdf
Unit IV Knowledge and Hybrid Recommendation System.pdf
 
VIT336 – Recommender System - Unit 3.pdf
VIT336 – Recommender System - Unit 3.pdfVIT336 – Recommender System - Unit 3.pdf
VIT336 – Recommender System - Unit 3.pdf
 
OOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfOOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdf
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
 
MongoDB.pdf
MongoDB.pdfMongoDB.pdf
MongoDB.pdf
 
ANGULARJS.pdf
ANGULARJS.pdfANGULARJS.pdf
ANGULARJS.pdf
 
JQUERY.pdf
JQUERY.pdfJQUERY.pdf
JQUERY.pdf
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301
 
CNS - Unit v
CNS - Unit vCNS - Unit v
CNS - Unit v
 
Cs8792 cns - unit v
Cs8792   cns - unit vCs8792   cns - unit v
Cs8792 cns - unit v
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit iv
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit iv
 
Cs8792 cns - unit i
Cs8792   cns - unit iCs8792   cns - unit i
Cs8792 cns - unit i
 
Java quick reference
Java quick referenceJava quick reference
Java quick reference
 
Cs8792 cns - Public key cryptosystem (Unit III)
Cs8792   cns - Public key cryptosystem (Unit III)Cs8792   cns - Public key cryptosystem (Unit III)
Cs8792 cns - Public key cryptosystem (Unit III)
 
Cryptography Workbook
Cryptography WorkbookCryptography Workbook
Cryptography Workbook
 
Cns
CnsCns
Cns
 
Cs6701 cryptography and network security
Cs6701 cryptography and network securityCs6701 cryptography and network security
Cs6701 cryptography and network security
 
Compiler question bank
Compiler question bankCompiler question bank
Compiler question bank
 
Compiler gate question key
Compiler gate question keyCompiler gate question key
Compiler gate question key
 

Recently uploaded

Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 

Recently uploaded (20)

Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
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> ) }