Chapter 6 Updated
Chapter 6 Updated
ABSTRACT
This chapter introduces React’s core
concepts: building UIs with reusable
components, writing UI with JSX,
passing data using props, and rendering
lists with map and filter. It also covers
basic routing for navigation in single-
page apps.
CHAPTER 6
React JS
0
Chapter 6
React JS
Introduction
✓ The React.js is an open-source JavaScript framework and library developed by Facebook. It’s
used for building interactive user interfaces and web applications quickly and efficiently.
✓ Primary role of React in an application is to handle the view layer of that application just like
the V in a model-view-controller (MVC) pattern by providing the best and most efficient
rendering execution.
✓ Before starting we should have a basic understanding of HTML, CSS, DOM, ES6, Node.js and
npm.
✓ Because of its ability to create fast, efficient, and scalable web applications, React has gained
stability and popularity. Thousands of web applications use it today, from well-established
companies to new start-ups. Some of the popular examples are as under:
Facebook, Instagram, Netflix, Reddit, Uber, Airbnb, The New York Times, Khan Academy,
Codecademy, WhatsApp Web
History
✓ React was created by Jordan Walke, a software engineer at Meta, who initially developed a
prototype called "F-Bolt", later renaming it to "FaxJS".
✓ This early version is documented in Jordan Walke's GitHub repository. Influences for the
project included XHP, an HTML component library for PHP.
✓ React was first deployed on Facebook's News Feed in 2011 and subsequently integrated into
Instagram in 2012.
✓ In May 2013, at JSConf US, the project was officially open-sourced.
About React
✓ Component based approach: A component is one of the core building blocks of React. In
other words, we can say that every application you will develop in react will be made up of
pieces called components. Components make the task of building UIs much easier.
✓ Uses a declarative approach: Declarative programming is a programming paradigm that
expresses the logic of a computation without describing its control flow.
✓ DOM (Document Object Model) updates are handled gracefully.
✓ Reusable code.
1
Chapter 6
Virtual DOM
When something on the web page needs to change, React first updates this Virtual DOM.
Then, it efficiently compares the updated Virtual DOM with its previous version to find out
exactly what changed. Finally, it applies only the minimal necessary changes to the
Real DOM that the user sees in the browser.
This process makes updating web pages much faster and smoother than directly
manipulating the complex Real DOM every time something changes.
1. Initial View: You see the Navbar, Footer, Team A's score, current batsman's
name, and their score. React has a complete (Virtual DOM) of this.
2. Batsman Hits a Four:
o React gets the update: "batsman's score +4, Team score +4."
o It quickly makes a new Virtual DOM reflecting these only these two changes.
o React compares the new Virtual DOM to the old one. It instantly sees that
only batsman's individual score and the team's total score numbers have
changed.
3. Screen Update: React tells the browser: "Just update batsman's score and the
team's total. Leave everything else alone."
The scores update instantly and smoothly on your screen without the whole page
reloading.
SPA
In a React Single Page Application (SPA), smooth navigation relies on the Virtual DOM
and the <Link> component from react-router-dom.
How it works for your website with a consistent navbar and footer:
• Initial Load: React builds the entire UI (navbar, Home content, footer) as a Virtual
DOM blueprint. The browser then draws the Real DOM from this blueprint.
• Navigation (e.g., clicking "About"):
o You must use <Link to="/about">, not <a>. <Link> prevents a full page
reload.
o react-router-dom updates the URL, triggering React.
o React creates a NEW Virtual DOM for the "About" page.
o React's "diffing" algorithm compares the new "About" Virtual DOM with the old
"Home" one. It sees the navbar and footer are identical, but the content has
changed.
o React then tells the browser to only update the changed part of the Real
DOM (just the content area).
2
Chapter 6
Setup of React JS
• Step 1: Install Node.js installer for windows.
In npx you can create a react app without installing the package:
`npx create-react-app myApp`
This command is required in every app’s life cycle only once.
Run below command if not able to create a react app using above command.
`npm install -g create-react-app`
By creating a react app folder structure will be looked as shown in next topic called “Folder Structure”
image.
3
Chapter 6
4
Chapter 6
Folder Structure
Once a react app gets created, The folder structure looks as below.
node_modules
✓ In this folder, you will get various
folders of all the required
dependencies & packages that
may be used for building your react
app. For example – Webpack,
Babel, JSX, Jest & more.
✓ You not need to modify the
node_module.
✓ It is already configured with the
react app.
Public
5
Chapter 6
✓ If you put assets in the public folder and you have to give their reference in your project,
then you will have to use a special variable that is called PUBLIC_URL.
✓ A file that remains in the public folder, will be accessible by %PUBLIC_URL%.
For example –
<link rel=”icon” href=”%PUBLIC_URL%/favicon.ico” />
✓ When you run the npm build command to deploy your project, create-react-app will convert
%PUBLIC_URL% to the right absolute path of your application. So that it can work well if you
use host/client-side routing at a non-root URL
✓ favicon.ico
✓ This the default react icon that always remains in the public folder. you can also put here
your own project icon but the icon extension must be .ico and the icon name may be
anything.
✓ You can remove favicon.ico when you place a new favicon for your project/website.
✓ When you open your app in the web browser, you will see an icon in the tab on the left side.
It is the symbol of your application. So, you should not leave it.
index.html
✓ This is the index file that displays when the react app opens in the web browser. It contains
the HTML template of the react application.
✓ index.html file is the root file of the react app. Everything will be rendered through it on the
front end. So, Don’t try to change & remove this file from the public folder.
Note – index.html must exist in the public folder and you must not delete it otherwise you
will get an error.
✓ These are the logos of react js. It is placed just for the initial view of react app. you can
remove/leave it depends on you.
manifest.json
✓ manifest.json provides the metadata like short_name, name & icons in the form of JSON for
a react application. It may be installed on the mobile or desktop. So that you can directly
open the react application with its installed favicon.
6
Chapter 6
✓ Due to the manifest.json file, users get a notification to install react application on their
mobile or desktop.
✓ You must not remove manifest.json but you can modify JSON values according to your
project
robots.txt
✓ The robot.txt file is given just for SEO purposes. As a developer, you need not do anything
with this file. This file is not related to development.
src
✓ In the src folder, You can put all the js, CSS, images, components file & other assets of your
projects.
✓ By default, we get the following files that are necessary to understand their usages. you can
create your own files according to these files for developing your projects.
App.css
✓ App.css file contains a default CSS code and import into the App.js file. It is also global, you
can import another file. You can create your own CSS file like App.css but make sure that its
name must start with the uppercase letter and.
App.js
✓ App.js is a parent component file of your react app. It is imported into the index.js file to
render content/HTML in the root element that remains in public/HTML.
✓ You can also create your own component file according to App.js but make sure that its
extension must be .js and its name must start with an uppercase letter (recommended).
✓ for an example – Myapp.js.
App.test.js
✓ App.test.js gives us a testing environment. Basically, it’s written code to protect the react
application to be crashed.
7
Chapter 6
✓ We also need not modify & remove this file from the react application.
index.css
✓ index.css file contains some default css code for index.js. You can modify/add some new
CSS code according to your project design pattern.
index.js
✓ index.js file is an entry point of react app. Means that all the component renders through
this file to the index.html.
✓ Basically, your application executes properly with the help of index.js. Even all the js files of
components are imported in this file.
✓ for example – As App.js file is imported with using import App from './App' .
✓ If you want to add your own module then you also have to import your own Myapp.js file
using the import Myapp from './Myapp' in index.js file;
logo.svg
✓ This is the default logo of react js. You can remove it and place your project logo.
reportWebVital.js
✓ reportWebVital.js is related to the speed of your application. You also need not to do
anything with this file.
setupTest.js
✓ In this file, @testing-library/jest-dom is imported. You need not modify and remove it from
the application
.gitignore
✓ .gitignore file is used to ignore those files that have not to be pushed to the git.
✓ By default, dependencies, testing folders/files are defined in the .gitignore. When you push
your app to the git, these folders/files will not be pushed.
8
Chapter 6
package-lock.json
package.json
✓ All the dependencies are defined in this file. It maintains which dependencies are necessary
for our application
README.md
✓ In this file, Some instructions are written to configure and set up the react application.
✓ Even you can also write more instructions for your project that will help the developer to
configure it easily.
<!-- manifest.json provides metadata used when your web app is installed on a user's
mobile device or desktop. -->
9
Chapter 6
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!-- This HTML file is a template. If you open it directly in the browser, you will see an
empty page. You can add webfonts, meta tags, or analytics to this file. The build step will
place the bundled scripts into the <body> tag. -->
</body>
</html>
Index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
// If you want to start measuring performance in your app, pass a function to log results (for
example: reportWebVitals(console.log)) or send to an analytics endpoint.
reportWebVitals();
10
Chapter 6
React render
React renders HTML to the web page by using a function called createRoot() and its method render().
The render() method is then called to define the React component that should be rendered.
When building web applications in React, you use two packages—react and react-dom.
The react package holds the react source for components, state, props and all the code that is react.
The react-dom package as the name implies is the glue between React and the DOM. Often, you will only use it
for one single thing: mounting your application to the index.html file with ReactDOM.render().
React components are such a great way to organize UI that it has now spread to mobile to react is used in web
and in mobile. react-dom is used only in web apps.
Note: Previously we had to import React because the JSX is converted into regular Javascript that use react's
React.createElement method.
But, React has introduced a new JSX transform with the release of React 17 which automatically transforms JSX
without using React.createElement. This allows us to not import React, however, you'll need to import React
to use Hooks and other exports that React provides. But if you have a simple component, you no longer need
to import React. All the JSX conversion is handled by React without you having to import or add anything.
They work together like a brain (react) and a hand (react-dom)—react decides what to show, and
react-dom makes it appear on screen.
• react
o Understands JSX (<h1>, <button>, etc.)
o Manages component logic (useState, rendering, updating)
• react-dom
o Finds document.getElementById('root')
o Injects React's virtual DOM into the actual browser DOM
o Updates the DOM when state/props change
11
Chapter 6
App.js
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
12
Chapter 6
React Components
✓ A react component is a JavaScript function that you can sprinkle with markup
✓ React lets you create components, reusable UI elements for your app.
✓ In a React app, every piece of UI is a component.
✓ React components are regular JavaScript functions except:
o Their names always begin with a capital letter.
o They return JSX markup.
Example1
Build basic react app that display “Hello World” in browser.
This App.js file is imported as a component in index.js file as we have shown above.
This App.js file can also be considered as a component. As we are exporting it and importing
in the file index.js. We can reuse this component just by importing it.
13
Chapter 6
App.js is the default component file. If you don’t want to make changes in this component
file then create your own component file i.e. Myapp.js and make changes in it. And call your
component file in index.js.
Myapp.js
function Myapp() {
return (
<div>
<h1>Hello World!</h1>
</div>
);
}
export default Myapp;
14
Chapter 6
2) Create file named ex1.js as a component and import this component in App.js or
Myapp.js file.
Myapp.js
import Ex1 from "./Ex1";
function Myapp() {
return (
<div>
<Ex1/>
</div>
);
}
export default Myapp;
Ex1.js
function Ex1() {
return(
<div>
<h1>Hello World!</h1>
</div>
)
}
export default Ex1;
This App.js or Myapp.js file is imported as a component in index.js file as we have shown
above.
Note: Please try to follow last method of importing component to App.js or Myapp.js file. In this file just
import component and call this component as shown in above example.
function Ex1() {
return (
// If you copy and paste above code as it is here, it will not work and give an error:
“Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment
<>...</>? “
)
}
export default Ex1
<div>
<h1>LJU students</h1>
<ul>
16
Chapter 6
<li>CSE</li>
<li>IT</li>
<li>CE</li>
</ul>
</div>
If you don’t want to add an extra <div> to your markup, you can write <> and </> instead if
“<div>” tag
This empty tag is called a Fragment. Fragments let you group things without leaving any trace
in the browser HTML tree.
4. Passing expression
If you want to dynamically specify the src or alt text in img tag. You could use a value from
JavaScript by replacing " and " with { and }
17
Chapter 6
Note: The className="pic", which specifies an "pic" CSS class name that applies css to the
image
src={pic} that reads the value of pic which is imported. That’s because curly braces let you
work with JavaScript right there in your markup!
You can only use curly braces in two ways inside JSX:
As text directly inside a JSX tag: <h1>{name}'s To Do List</h1> works, but <{tag}> Test’s
To Do List</{tag}> will not work.
As attributes immediately following the = sign: src={pic} will read the avatar variable,
but src="{pic}" will pass the string "{pic}".
OR
function Subtraction() {
var mystyle = {backgroundColor:'red',color:'#fff'};
return(
<div>
<h1 style={mystyle}>Subtraction : {7-4}</h1>
</div>
)
};
18
Chapter 6
JSX Comments
To write comments in React (JSX), we need to wrap them in curly braces.
Function comment() {
Return(
{/* this works */ }
)
}
The curly braces tell the JSX parser to parse the code inside as JavaScript, and not a string.
Since the contents inside are parsed as JavaScript, this enables us to also do multi-line or
single-line comments:
function comment(){
return (
<>
{
/*
mult-line
test
*/
}
{
// single-line test
}
</>
)}
In the case of a single-line comment, You cannot have the ending bracket in the same line,
because that will break everything.
19
Chapter 6
Example
Write React code to render a component with the following data:
• A heading in italics, blue color, and font-size 25px.
• An image.
• An ordered list of 3 fruits that start with the letter "A".
• The current time and current date in red color, centered.
App1.js
import img1 from "./image.jpg"
function App1() {
const date=new Date().toLocaleDateString()
const time=new Date().toLocaleTimeString()
return (
<div>
<h1 style = {{color:"blue", fontStyle: "italic", fontSize: "25px"}}>Hello, Good Morning!</h1>
<h3> List of fruits</h3>
<ol type="A">
<li>Apple</li>
<li>Lichi</li>
<li>Kiwi</li>
</ol>
<img src={img1} alt="image"/>
<h6>Current Date: {date}</h6>
<h6>Current Time: {time}</h6>
</div>
)}
export default App1;
Note: Styling info must be written inside two sets of curly braces {{}}. If dashed property name
is used like background-color, font-size, then we have to use camel case names of properties
like backgroundColor, fontSize.
**new Date().toLocaleDateString(): The toLocaleDateString() method returns the date (not the
time) of a date object as a string, using locale conventions.
**new Date().toLocaleTimeString(): The toLocaleTimeString() method returns the time portion
of a date object as a string, using locale conventions.
20
Chapter 6
✓ In React, the Map method used to traverse and display a list of similar objects of a
component.
✓ Often, we find ourselves needing to take an array and modify every element in it. Use
.map() whenever you need to update data inside an array (by mapping over it!).
✓ A map is not the feature of React. Instead, it is the standard JavaScript function that could
be called on any array.
✓ The map() method creates a new array by calling a provided function on every element in
the calling array.
Example-1
Write React code to render a component to display all array elements in h2 tag using map
function.
Map1.js
import React from 'react';
function Map1() {
const arr=[1,2,3,4,5];
return (
<div>
<h1>Example of mapping</h1>
{
arr.map((value)=>
{
return <h2>Array Element= {value}</h2>
})
}
</div>
)
}
export default Map1
Myapp.js
import Map1 from "./Map1";
function Myapp() {
return (
<div>
21
Chapter 6
<Map1/>
</div>
);
}
export default Myapp;
This Myapp.js file is imported as a component in index.js file
Output:
Example-2
Write React code to render a component having an array of strings and convert it in
Uppercase using map method.
Arraymap.js
const Arraymap = () => {
const arr=["a","b","c","d","e"];
return (
<div>
<h1>map function</h1>
{ arr.map((value)=> {
return <p>array values= {value.toUpperCase()}</p>
})
}
</div>
)}
export default Arraymap
Output:
map function
22
Chapter 6
array values= A
array values= B
array values= C
array values= D
array values= E
Example-3
We have an array of numbers and we want to multiply each of these numbers by 5. Write
React code to render a component to display these multiplied numbers using map function.
Map2.js
function Map2() {
let arr = [2, 4, 6, 3, 10, 12]
return (
<div>
<h1>Multiplication of numbers are as under: </h1>
{
arr.map((value)=>
{
return <h2>{value} * 5 = {value * 5}</h2>
})
}
</div>
)
}
export default Map2
Output:
23
Chapter 6
Example-4
Write React code to render a component which displays images using map function.
Map3.js
import React from 'react';
import img1 from "./img1.png" //import image from same folder
import img2 from "./img2.png" //import image from same folder
function Map3() {
const images=[{id:2,pic:img1},{id:2,pic:img2}];
return (
<div>
{images.map((val) => {
return <img src={val.pic} heigth="200px" width="200px" alt="logo" />
})}
</div>
)
}
export default Map3
Output: This will display two images.
24
Chapter 6
[
undefined,
undefined,
undefined,
<h2>4</h2>,
<h2>5</h2>,
undefined,
<h2>6</h2>,
<h2>4</h2>,
undefined,
undefined
]
React takes that array and renders only the valid JSX elements. It skips all the undefineds, so you only see:
Array Elements = 4
Array Elements = 5
Array Elements = 6
Array Elements = 4
Best Practice:
To avoid unnecessary undefined values (even if they’re harmless here), prefer:
arr.filter(val => val > 3).map(val => <h2>{val}</h2>)
It keeps your logic cleaner, predictable, and debug-friendly.
25
Chapter 6
Keys are used in React to identify which items in the list are changed, updated, or deleted. In
other words, we can say that keys are used to give an identity to the elements in the lists. It is
recommended to use a string as a key that uniquely identifies the items in the list.
List.js
function List() {
const students = [
{id: 1, name: 'ABC'},
{id: 2, name: 'XYZ'},
{id: 3, name: 'PQR'}
];
return(
<ul>
{
students.map((student) =>
{
return <li key={student.id}>{student.name}</li>
})
}
</ul>
)
}
export default List
OR
26
Chapter 6
List.js
function List() {
const students = [
{id: 1, name: 'ABC'},
{id: 2, name: 'XYZ'},
{id: 3, name: 'PQR'}
];
return(
<ul>
{
students.map((student,index) =>
{
return <li key={index}>{student.name}</li>
})
}
</ul>
)
}
export default List
27
Chapter 6
Filter
✓ filter() loops through data, and filters out data that doesn't match the criteria that we set.
✓ So, It's the process of looping through an array and including or excluding elements inside
that array based on a condition that you provide.
✓ It is also built in JavaScript function.
Write React component to skip digit “3” from an array and display all remaining digits of the
array.
Filt1.js
function Filt1() {
const arr = [1, 2, 3, 4, 5, 3, 7, 3, 9];
return (
<di>
<h1>
Array elements before applying filter:
<span style={{ color: "red" }}> {arr.join(", ")} </span>
</h1>
<h1>
Array elements after applying filter:
<span style={{ color: "red" }}> {newarr.join(", ")} </span>
</h1>
</div>
);
}
export default Filt1;
Output:
28
Chapter 6
To understand difference of output using map and filter refer below examples.
Example:
Write React code to filter out the numbers greater 6 using map/filter function.
Check difference in output using different methods.
Using Only map method
const ArrayMap_condition = () => {
const arr1=[1,2,3,4,5,6,7,8,9]
return (
<div>
<h1>using map/filter function</h1>
{
arr1.map((value)=>{
if(value <=6){
return <h1>array values= {value}</h1>
}
})
}
</div>
)
}
export default ArrayMap_condition
29
Chapter 6
OR
Using Only filter method
const ArrayMap_condition = () => {
const arr1=[1,2,3,4,5,6,7,8,9]
return (
<div>
<h1>using map/filter function</h1>
{
arr1.filter((value)=>value <=6){
return <h1>array values= {value}</h1>
}
})
}
</div>
)
}
export default ArrayMap_condition
30
Chapter 6
31
Chapter 6
React Props
✓ Props stand for "Properties." It is an object which stores the value of attributes of a tag and
work similar to the HTML attributes.
✓ React components use props to communicate with each other. Each component can pass
some information to other components by giving them props.
✓ Props are similar to function arguments. Props are passed to the component in the same
way as arguments passed in a function.
Let’s understand how to pass and read data using props by below example.
function Prop1 () {
var n = “ABC”;
return (
<div>
<Prop2 name={n} rollnum="101" marks="20" />
<Prop2 name="DEF" rollnum="102" marks="16" />
<Prop2 name="GHI" rollnum="103" marks="22.5" />
</div>
);
}
export default Prop1;
);
}
export default Prop2;
Output:
Example:
Write a React code to print car’s brand name and its model name which are passed as props
using JSON.
Ex2.js
import Ex3 from "./Ex3";
function Ex2() {
const carInfo = { brand: "Kia", name: "Sonet" };
return (
<div>
<h1>Details of car</h1>
<Ex3 car={ carInfo }/>
</div>
);
}
export default Ex2;
Ex3.js
import React from 'react';
function Ex3(props) {
33
Chapter 6
return(
<>
<h2>Car Brand: { props.car.brand } </h2>
<h3>Car Name: { props.car.name }</h3>
</>
);
}
export default Ex3;
Output:
Example
Write a program using ReactJS in which you’ve to create two variable names -Student_name
and University_name, these both values should be passed to another component
names_Details where these values are printed using props.
Example1.js
import Example from "./Example";
function Example1 () {
const Details = {Student_name: "abc", University_name: "LJU"};
return (
<div>
<Example data ={ Details }/>
</div>
)}
export default Example1
Example.js
function Example(props) {
return(
<h2> My name is {props.data.Student_name}.
34
Chapter 6
Example
Build a React app that displays a list of products using props.
• Create a ProductCard component to show product details like title, price, rating, and
image.
• Use a ProductList component to store product data and display multiple ProductCard
components using .map().
ProductList.js
import ProductCard from './ProductCard';
function ProductList() {
const products = [
{
title: "iPhone 15 Pro",
price: "$999",
rating: 4.8,
image: "https://example.com/iphone.jpg"
},
{
title: "Samsung Galaxy S24",
price: "$899",
rating: 4.5,
image: "https://example.com/galaxy.jpg"
},
{
title: "Google Pixel 8",
price: "$799",
rating: 4.6,
image: "https://example.com/pixel.jpg"
}
];
35
Chapter 6
return (
<div>
<h1>Our Products</h1>
<ProductCard productList={products} />
</div>
);
}
36
Chapter 6
React Events
To handle events with React elements is very similar to handle events with DOM events. There
are some syntax differences as below:
React events are named using camelCase, rather than lowercase as we used to do in HTML.
In HTML:
<button onclick="demofunction()">
LJ University
</button>
In React:
<button onClick = { demoFunction }>
LJ University
</button>
Another difference is that we cannot return false to prevent default behavior in React. We must
call preventDefault explicitly.
preventDefault is used to prevent the default form behavior of submitting.
In HTML
<form onsubmit="console.log (' You clicked submit. '); return false">
<button type="submit">Submit</button>
</form>
In React
function Form () {
function handleSubmit (e) {
e.preventDefault ();
alert (' You clicked submit.');
}
return (
<form onSubmit = {handleSubmit}>
37
Chapter 6
<button type="submit">Submit</button>
</form>
);
}
38
Chapter 6
<Event1/>
</div>
);
}
export default App;
Output:
Event2.js
import React from 'react';
function Event2() {
function handleChange(event) {
console.log (event.target.value);
}
return (
<input type=”text” name="firstName" onChange={handleChange} />
);
}
export default Event2;
App.js
import Event2 from "./Event2"
function App() {
return (
<div>
<Event2/>
</div>
);
39
Chapter 6
}
export default App;
Output:
40
Chapter 6
return (
<form onSubmit = {handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}export default Event4;
App.js
import Event3 from "./Event4"
41
Chapter 6
function App() {
return (
<div>
<Event4/>
</div>
);
}
export default App;
Output:
On page load, the alert pops up: "Welcome to LJU"
But when you click the button, nothing happens because the onClick handler is now undefined.
Explaination:
42
Chapter 6
React Routing
Create React App doesn't include page routing. React Router is the most popular solution for
page routing.
Folder Structure
To create an application with multiple page routes, let's first start with the file structure.
Within the src folder, we'll create a folder named routing with several files:
src\routing\:
• Home.js
• Shop.js
• Contact.js
• Nopage.js
Each file will contain a very basic React component.
✓ BrowserRouter: It is used to keep your UI in sync with the URL. It is the parent
component that is used to store all of the other components.
✓ Routes: An application can have multiple <Routes>. Routes are chosen based on the
best match instead of being traversed in order.
✓ 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.
✓ Link: Link component is used to create links to different routes and implement
navigation around the application. It works like HTML anchor tag.
Note:Do not use anchor tags instead of <Link> components because using anchor tags would not allow applications to
remain Single Page Application (SPA). HTML anchor tag would trigger a page reload or page refresh when clicked.
Example:
• Create react app to perform tasks as asked.
First create files as asked below in routing folder
43
Chapter 6
• Create Main.js file which contains Links for Home, Shop and Product page. Also, add
functionality of page routing.Finally call Main.js in App.js.
App.js App.css
Main.js
(Include all
component and
routing)
App.js
import './App.css';
import Main from "./routing/Main.js";
function App() {
return (
<div>
<Main/>
</div>
);
}
export default App;
(Below all files are inside routing folder in src folder.)
routing/Main.js
import React from 'react';
import {BrowserRouter as Router,Route,Routes,Link} from "react-router-dom";
44
Chapter 6
</div>
);
}
export default Main
Setting the path to * will act as a catch all undefined URLs and display 404 error page.
routing/Home.js
import React from 'react'
function Home(){
return (
<div>
<h1>Home page</h1>
</div>
)
}
45
Chapter 6
routing/Shop.js
import React from 'react'
function Shop(){
return (
<div>
<h1>Shop page</h1>
</div>
)
}
export default Shop
routing/Contact.js
import React from 'react'
function Contact() {
return (
<div>
<h1>Contact Detail</h1>
</div>
)
}
export default Contact
routing/Nopage.js
import React from 'react'
function Nopage() {
return (
<div>
<h1>404 Page not Found</h1>
</div>
)
}
export default Nopage
App.css (It is Not compulsory to add this file in this example. Added css for the reference only)
.main-route ul {
46
Chapter 6
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #000;
margin-bottom: 50px;
}
.main-route li {
float: left;
}
.main-route li a {
display: block;
color: white;
text-align: center;
padding: 20px;
text-decoration: none;
}
.main-route h1{ color: red; text-align: center;
47
Chapter 6
Miscellaneous Examples
48
Chapter 6
export default M1
Example3: Create react app to pass product image, name and price as properties from one
component to another component. Add an array of objects with pic, name and price
properties of 2 products. Display Image name and price of the products in browser using
map method.
P.js (Pass the data)
import P1 from "./P1";
import img1 from "./img1.png"
import img2 from "./img2.png"
function P(){
const prod=[
{
pic:img1,
name:"Product1",
price:3000
},
{
49
Chapter 6
pic:img2,
name:"Product2",
price:3000
}
]
return(
<div>
<P1 info={prod}/>
</div>
)
}
export default P
P1.js (Read the data)
import React from "react";
function P1(prop){
return(
<>
{
prop.info.map((pr)=>{
return (
<div>
<img src={pr.pic} alt="No Image" />
<h2>{pr.name}</h2>
<h3>{pr.price}</h3>
</div>
)
})
}
</>
)
}
export default P1
Import P component in App.js file
50
Chapter 6
Example 4
Create a React app to perform the following tasks using functional components:
Implement the following components in your React application:
• Main.js to set up the router and define the routes.
• Home.js for the Home page.
• Product.js for the Product page.
1. Create a React Router:
o Include two routes: Home and Product. Implement navigation between these
routes.
2. Create the following routes and components:
o When a user clicks on the Home page link, it should navigate to the Home page and
display "Welcome to LJU" within an <h1> heading with blue color. Also, include link
to product page.
o A Product page that displays three products' information (name, price, and image)
using props. When a user clicks on the Product page link, it should navigate to the
Product page and display three products' information name, price and product
image using props.
Main.js
import {BrowserRouter as Router,Route,Routes,Link} from "react-router-dom";
import Home from './home';
import Product from './product'
import Nopage from './nopage';
import img1 from "./img1.jpg"
import img2 from "./img2.jpg"
import img3 from "./img3.png"
function Main() {
const products=[{name:"p1",price:20000, pic:img1},{name:"p2",price:14000,
pic:img2},{name:"p3",price:40000, pic:img3}]
return (
<div>
<Router baseName="/calendar">
<div className='main-route'>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/product">Product</Link></li>
</ul>
</div>
51
Chapter 6
<Routes>
<Route path="/" element={<Home/>}/>
<Route path="/product" element={<Product info={products}/>}/>
<Route path="*" element={<Nopage/>}/>
</Routes>
</Router>
</div>
);
}
export default Main
home.js
function Home(){
return (
<div>
<h1 style={{color:"blue"}}>Home page</h1>
<a href="/product">Product</a>
</div>
)
}
export default Home
nopage.js
function Nopage() {
return (
<div>
<h1>404 Page not Found</h1>
</div>
)
}
export default Nopage
product.js
const Product = (Props)=>{
return(
<div>
{
Props.info.map((p)=>{
return(
<div>
52
Chapter 6
Example 5
Create a component to perform the tasks as described below:
1. Add a text field and a submit button.
- While changing the value in the text field, display it below the form.
- Display this text field value in an alert box upon submitting it.
2. Add a button to perform click and double-click event tasks.
- On click event, display message in h3 tag “You clicked once”.
- On double-click event, display message in h3 tag “You clicked twice”.
- Message should be displayed below the button.
function Map1() {
const arr=[1,2,3,4,5];
function handleSubmit (e) {
e.preventDefault ();
alert (document.getElementById('uname').value);
}
function handleclick(){
document.getElementById('test1').innerHTML = “You clicked once”
}
function handledoubleclick(){
document.getElementById('test1').innerHTML = “You clicked twice”
}
function handleChange(event) {
document.getElementById('test').innerHTML =event.target.value;
53
Chapter 6
}
return (
<div>
<form onSubmit = {handleSubmit}>
<input type="text" id="uname" onChange={handleChange}></input>
<input type="submit"/>
</form>
<button style={{backgroundColor:'black',padding:"20px",color:"white"}}
onClick={handleclick} onDoubleClick={handledoubleclick}>Click</button>
<h1 id="test1">Click/DoubleClick event</h1>
</div>
)
}
54
Chapter 6
55