0% found this document useful (0 votes)
6 views35 pages

Reactjs Lab Manual 6th Sem

The document is a lab manual for a ReactJS course (BCSL657B) at Alva's Institute of Engineering & Technology, detailing course outcomes, objectives, and experiments for students. It outlines the assessment structure, including Continuous Internal Evaluation (CIE) and Semester End Examination (SEE), along with suggested learning resources. The manual includes practical experiments that focus on developing real-time web applications using React, managing state, and implementing routing and API interactions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views35 pages

Reactjs Lab Manual 6th Sem

The document is a lab manual for a ReactJS course (BCSL657B) at Alva's Institute of Engineering & Technology, detailing course outcomes, objectives, and experiments for students. It outlines the assessment structure, including Continuous Internal Evaluation (CIE) and Semester End Examination (SEE), along with suggested learning resources. The manual includes practical experiments that focus on developing real-time web applications using React, managing state, and implementing routing and API interactions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

ALV A’SINSTITUTEOFENGINEERING&TECHNOLOGY

(A Unit of Alva’s Education Foundation)


Shobhavana Campus,Mijar,Moodbidri,D.K–574225
(Accredited by NAAC with A+ Grade)
Affiliated to VTU Belagavi, Approved by AICTE, NewDelhi
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
(Accredited by NBA, NewDelhi)

REACTJS
Lab Manual
(SubjectCode:BCSL657B)
[As per Choice Based Credit System (CBCS) scheme]

SEMESTER–VI

PREPAREDBY,
Mr. Giridhar Gowda (Sr.Asst Professor)
APPROVEDBY,
Dr.Manjunath Kotari(Professor and Head of CSE)
COURSEOUTCOMES(CO’S)
Co Course outcomes Blooms Target
Numbers level level
Construct a real time web application using
stateful component and props with
BCSL657B.1 parent , child components.. Apply(L2) 2
Develop a Counter application that
demonstrates state management with
BCSL657B.2 useState hook and To-do list application Apply(L2) 2
using React functional components
Build React application that demonstrates
component composition, props and React
BCSL657B.3 Apply(L2) 2
form to validate user information.
Design ProfileCard component to display
the user’s profile information and
Reminder application that dynamically
BCSL657B.4 effects the application based on props or Apply(L2) 2
state.
Demonstrate routing and class-based
BCSL657B.5 component concept for implementing Apply(L2) 2
dynamic web application.

CO-PO/CO-PSO MAPPING MATRIX


CONo. PO1 PO PO PO PO PO PO PO PO PO PO PO PS PS PS
2 3 4 5 6 7 8 9 10 11 12 O1 O2 O3
BCSL657B.1
2 1 2 2 2 2 2 2 2 2 2 2

BCSL657B.2 2 1 2 2 2 2 2 2 2 2 2 2
BCSL657B.3 2 1 2 2 2 2 2 2 2 2 2 2
BCSL657B.4
2 1 2 2 2 2 2 2 2 3 3 2
BCSL657B.5 2 1 2 2 2 2 2 2 2 3 3 2
Avg 2.0 1.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.4 2.4 2.0
REACTJS LAB

REACTJS Semester 6
Course Code BCSL657B CIE Marks 50
Teaching Hours/Week(L:T:P:S) 0:0:1:0 SEE Marks 50
Credits 01 Exam 2
Hours
Examination type(SEE) Practical
Course objectives:
● Enable students to develop React applications utilizing functional and class-based
components, effectively managing state with hooks and lifecycle methods .
● Introduce, how to pass data dynamically between parent and child components
using props, ensuring modular and reusable component design.
● Create dynamic and responsive applications, integrating forms, validation, task
management systems, and styled components.
● Use React Router for navigation, external API integration for dynamic data
handling, and CSS styling techniques for modern UI/UX design.
Sl.No Experiments
1 Use create-react-app to set up a new project. Edit the App.js file to include a stateful
component with useState. Add an input field and a element that displays text based on
the input. Dynamically update the content as the user types..
2 Develop a React application that demonstrates the use of props to pass data from a
parent component to child components. The application should include the parent
component named App that serves as the central container for the application. Create
two separate child components, Header: Displays the application title or heading.
Footer: Displays additional information, such as copyright details or a tagline. Pass
data (e.g., title, tagline, or copyright information) from the App component to the
Header and Footer components using props. Ensure that the content displayed in the
Header and Footer components is dynamically updated based on the data received
from the parent component.
3 Create a Counter Application using React that demonstrates state management
with the useState hook. Display the current value of the counter prominently on
the screen. Add buttons to increase and decrease the counter value. Ensure the
counter updates dynamically when the buttons are clicked. Use the useState hook
to manage the counter's state within the component. Prevent the counter from
going below a specified minimum value (e.g., 0). Add a "Reset" button to set the
counter back to its initial value. Include functionality to specify a custom
increment or decrement step value.
4 Develop a To-Do List Application using React functional components that
demonstrates the use of the useState hook for state management. Create a functional
component named ToDoFunction to manage and display the todo list. Maintain a list
of tasks using state. Provide an input field for users to add new tasks. Dynamically
render the list of tasks below the input field. Ensure each task is displayed in a user-
friendly manner. Allow users to delete tasks from the list. Mark tasks as completed
or pending, and visually differentiate them.
5 Develop a React application that demonstrates component composition and the use
of props to pass data. Create two components: FigureList: A parent component
responsible for rendering multiple child components. BasicFigure: A child
component designed to display an image and its associated caption. Use the
FigureList component to dynamically render multiple BasicFigure components. Pass
image URLs and captions as props from the FigureList component to each
BasicFigure component. Style the BasicFigure components to display the image and
caption in an aesthetically pleasing manner. Arrange the BasicFigure components

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 1


REACTJS LAB

within the FigureList in a grid or list format. Allow users to add or remove images
dynamically. Add hover effects or animations to the images for an interactive
experience.
6 Design and implement a React Form that collects user input for name, email, and
password. Form Fields are Name, Email, Password. Ensure all fields are filled before
allowing form submission.Validate the email field to ensure it follows the correct
email format (e.g., example@domain.com). Optionally enforce a minimum password
length or complexity. Display error messages for invalid or missing inputs. Provide
visual cues (e.g., red borders) to highlight invalid fields. Prevent form submission
until all fields pass validation. Log or display the entered data upon successful
submission (optional). Add a "Show Password" toggle for the password field.
Implement clientside sanitization to ensure clean input.
7 Develop a React Application featuring a ProfileCard component to display a user's
profile information, including their name, profile picture, and bio. The component
should demonstrate flexibility by utilizing both external CSS and inline styling for its
design. Display the following information: Profile picture, User's name, A short bio
or description Use an external CSS file for overall structure and primary styles, such
as layout, colors, and typography. Apply inline styles for dynamic or specific styling
elements, such as background colors or alignment. Design the ProfileCard to be
visually appealing and responsive. Ensure the profile picture is displayed as a circle,
and the name and bio are appropriately styled. Add hover effects or animations to
enhance interactivity. Allow the background color of the card to change dynamically
based on a prop or state
8 Develop a Reminder Application that allows users to efficiently manage their tasks.
The application should include the following functionalities: Provide a form where
users can add tasks along with due dates. The form includes task name,Due date,An
optional description. Display a list of tasks dynamically as they are added. Show
relevant details like task name, due date, and completion status. Include a filter option
to allow users to view all Tasks and Display all tasks regardless of status. Show only
tasks marked as completed. Show only tasks that are not yet completed.
9 Design a React application that demonstrates the implementation of routing using the
react-router-dom library. The application should include the Navigation Menu: Create
a navigation bar with links to three distinct pages, Home, About, Contact. Develop
separate components for each page (Home, About, and Contact) with appropriate
content to differentiate them. Configure routes using react-router-dom to render the
corresponding page component based on the selected link. Use BrowserRouter and
Route components for routing. Highlight the active link in the navigation menu to
indicate the current page
10 Design a React application featuring a class-based component that demonstrates the
use of lifecycle methods to interact with an external API. The component should fetch
and update data dynamically based on user interactions or state changes. Use the
componentDidMount lifecycle method to fetch data from an API when the
component is initially rendered. Display the fetched data in a structured format, such
as a table or list. Use the componentDidUpdate lifecycle method to detect changes in
the component's state or props. Trigger additional API calls to update the displayed
data based on user input or actions (e.g., filtering, searching, or pagination).
Implement error handling to manage issues such as failed API requests or empty data
responses. Display appropriate error messages to the user when necessary. Allow
users to perform actions like filtering, searching, or refreshing the data. Reflect
changes in the displayed data based on these interactions.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 2


REACTJS LAB

Course outcomes(Course SkillSet):


At the end of the course the student will be able to:

• Illustrate React basics and state components


• Develop React applications that utilize component composition, passing data through props
• Use dynamic state updates, event handling, and custom logic to increment, decrement, and
reset state values
• Implement forms in React that collect and validate user input.
• Demonstrate interaction with external APIs, dynamic content generation and manage state
in real-time applications.

Assessment Details(both CIE and SEE)


The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE)
is 50%. The minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of
50) and for the SEE minimum passing mark is 35% of the maximum marks (18 out of 50 marks).
A student shall be deemed to have satisfied the academic requirements and earned the credits
allotted to each subject/ course if the student secures a minimum of 40% (40 marks out of 100) in
the sum total of the CIE (Continuous Internal Evaluation) and SEE (Semester End Examination)
taken together

Continuous Internal Evaluation(CIE):


CIE marks for the practical course are 50 Marks.
The split-up of CIE marks for record/ journal and test are in the ratio 60:40
● Each experiment is to be evaluated for conduction with an observation sheet and
record write-up. Rubrics for the evaluation of the journal/write-up for
hardware/software experiments are designed by the faculty who is handling the
laboratory session and are made known to students at the beginning of the practical
session.
● Record should contain all the specified experiments in the syllabus and each
experiment write-up will be evaluated for 10 marks.
● Total marks scored by the students are scaled down to 30 marks (60% of maximum
marks).
● Weightage to be given for neatness and submission of record/write-up on
time.
● Department shall conduct a test of 100 marks after the completion of all
the experiments listed in the syllabus.
● In a test, test write-up, conduction of experiment, acceptable result, and
procedural knowledge will carry a weightage of 60% and the rest 40% for
viva-voce.
● The suitable rubrics can be designed to evaluate each student’s
performance and learning ability.
● The marks scored shall be scaled down to 20 marks (40% of the
maximum marks).
The Sum of scaled-down marks scored in the report write-up/journal and
marks of a test is the total CIE marks scored by the student.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 3


REACTJS LAB

Semester End Evaluation (SEE):


• SEE marks for the practical course are 50 Marks.
• SEE shall be conducted jointly by the two examiners of the same institute, examiners are
appointed by the Head of the Institute.
• The examination schedule and names of examiners are informed to the university before
the conduction of the examination. These practical examinations are to be conducted
between the schedule mentioned in the academic calendar of the University.
• All laboratory experiments are to be included for practical examination.
• (Rubrics) Breakup of marks and the instructions printed on the cover page of the answer
script to be strictly adhered to by the examiners. OR based on the course requirement
evaluation rubrics shall be decided jointly by examiners.
• Students can pick one question (experiment) from the questions lot prepared by the
examiners jointly.
• Evaluation of test write-up/ conduction procedure and result/viva will be conducted jointly
by examiners.
General rubrics suggested for SEE are mentioned here, writeup-20%, Conduction procedure
and result in -60%, Viva-voce 20% of maximum marks. SEE for practical shall be evaluated
for 100 marks and scored marks shall be scaled down to 50 marks (however, based on course
type, rubrics shall be decided by the examiners)
Change of experiment is allowed only once and 15% of Marks allotted to the procedure part
are to be made zero.
The minimum duration of SEE is 02 hours

Suggested Learning Resources:


Books:
1. Beginning React JS Foundations Building User Interfaces with ReactJS: An Approachable
Guide, Chris Minnick, Wiley publications , 2022
2. Learning React Functional Web Development with React and Redux , Alex Banks, Eve
Porcello · 2017

Web links and Video Lectures (e-Resources):

● https://www.youtube.com/watch?v=V9i3cGD-mts
● https://youtu.be/PHaECbrKgs0
● https://youtu.be/uvEAvxWvwOs
● https://www.geeksforgeeks.org/state-management-with-usestate-hook-in-react/
● https://youtu.be/KU-I2M9Jm68
● https://youtu.be/H63Pd_lXkeQ
● https://youtu.be/oTIJunBa6MA
● https://youtu.be/3EbYJrAOpUs

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 4


REACTJS LAB

PROGRAM 1
Use create-react-app to set up a new project. Edit the App.js file to include a stateful
component with useState. Add an input field and a element that displays text based on
the input. Dynamically update the content as the user types..

import React, { useState } from 'react';

function App() {
const [inputText, setInputText] = useState('');

const handleChange = (event) => {


setInputText(event.target.value);
};

return (
<div>
<input
type="text"
value={inputText}
onChange={handleChange}
placeholder="Type something..."
/>
<h1>{inputText}</h1>
</div>
);
}

export default App;

OUTPUT :

AIET MUDABIDRE

AIETMUDABIDRE

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 5


REACTJS LAB

PROGRAM 2
Develop a React application that demonstrates the use of props to pass data from a parent
component to child components. The application should include the parent component
named App that serves as the central container for the application. Create two separate
child components, Header: Displays the application title or heading. Footer: Displays
additional information, such as copyright details or a tagline. Pass data (e.g., title, tagline,
or copyright information) from the App component to the Header and Footer components
using props. Ensure that the content displayed in the Header and Footer components is
dynamically updated based on the data received from the parent component.

import React from "react";


import "./styles.css";

// Header Component
const Header = ({ title }) => {
return (
<header className="header">
<h1>{title}</h1>
</header>
);
};

// Footer Component
const Footer = ({ copyright }) => {
return (
<footer className="footer">
<p>{copyright}</p>
</footer>
);
};

// App Component (Parent)


const App = () => {
return (
<div className="app-container">
<Header title="React Props Demo" />
<main className="content">
<p>Welcome to our simple React application demonstrating props!</p>
</main>
<Footer copyright="© 2025 My React App. All rights reserved." />
</div>
);
};

export default App;

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 6


REACTJS LAB

/* style.css */
.header {
text-align: center;
border: 2px solid black;
padding: 20px;
border-radius: 10px;
margin: 3rem;
width: 400px;
}

.footer {
color: green;
font-size: 10px;

/* Setting Text Color */


.app-container {
color: crimson;
/* Set the desired color */
font-size: 20px;
}

OUTPUT :

ReactPropsDemo

WelcometooursimpleReactapplicationdemonstratingprops!
©2025MyReactApp.Allrights reserved.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 7


REACTJS LAB

PROGRAM 3
Create a Counter Application using React that demonstrates state management with the
useState hook. Display the current value of the counter prominently on the screen. Add
buttons to increase and decrease the counter value. Ensure the counter updates
dynamically when the buttons are clicked. Use the useState hook to manage the counter's
state within the component. Prevent the counter from going below a specified minimum
value (e.g., 0). Add a "Reset" button to set the counter back to its initial value. Include
functionality to specify a custom increment or decrement step value

import { useState } from "react";

export default function CounterApp() {


const [count, setCount] = useState(0);
const [step, setStep] = useState(1);

const increase = () => setCount(prev => prev + step);


const decrease = () => setCount(prev => (prev - step >= 0 ? prev - step : 0));
const reset = () => setCount(0);

return (
<div className="flex">
<div className="bg-white">
<h1 className="text-3xl">Counter App</h1>
<p className="text-4xl">{count}</p>
<div className="space">
<button onClick={increase} className="px-4 ">Increase</button>
<button onClick={decrease} className="px-6 ">Decrease</button>
<button onClick={reset} className="px-8">Reset</button>
</div>
<div>
<label className="block">Step Value:</label>
<input
type="number"
value={step}
onChange={(e) => setStep(Number(e.target.value))}
className="px-2"
/>
</div>
</div>
</div>
);
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 8


REACTJS LAB

OUTPUT :

CounterApp
21

IncreaseDecreaseReset
StepValue:03

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 9


REACTJS LAB

PROGRAM 4

Develop a To-Do List Application using React functional components that demonstrates the
use of the useState hook for state management. Create a functional component named
ToDoFunction to manage and display the todo list. Maintain a list of tasks using state. Provide
an input field for users to add new tasks. Dynamically render the list of tasks below the input
field. Ensure each task is displayed in a user-friendly manner. Allow users to delete tasks from
the list. Mark tasks as completed or pending, and visually differentiate them.

import { useState } from "react";

export default function ToDoFunction() {


const [tasks, setTasks] = useState([]);
const [task, setTask] = useState("");

const addTask = () => {


if (task.trim() === "") return;
setTasks([...tasks, { text: task, completed: false }]);
setTask("");
};

const toggleTaskCompletion = (index) => {


const updatedTasks = tasks.map((t, i) =>
i === index ? { ...t, completed: !t.completed } : t
);
setTasks(updatedTasks);
};

const deleteTask = (index) => {


setTasks(tasks.filter((_, i) => i !== index));
};

return (
<div className="p-4">
<h2 className="text-xl">To-Do List</h2>
<div className="flex">
<input
type="text"
className="border"
placeholder="Add a new task"
value={task}
onChange={(e) => setTask(e.target.value)}
/>
<button
className="bg-blue"
onClick={addTask}
>
Add
</button>
</div>

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 10


REACTJS LAB

<ul>
{tasks.map((t, index) => (
<li
key={index}
className={`flex2 ${t.completed ? "line-" : "text2"}`}
>
<span onClick={() => toggleTaskCompletion(index)}>{t.text}</span>
<button
className="text1"
onClick={() => deleteTask(index)}
>
&#10006;
</button>
</li>
))}
</ul>
</div>
);
}

OUTPUT :

To-DoList
Add a new task Add

• coding✖
• painting✖
• reading✖

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 11


REACTJS LAB

PROGRAM 5
Develop a React application that demonstrates component composition and the use of props to pass
data. Create two components: FigureList: A parent component responsible for rendering multiple child
components. BasicFigure: A child component designed to display an image and its associated caption.
Use the FigureList component to dynamically render multiple BasicFigure components. Pass image
URLs and captions as props from the FigureList component to each BasicFigure component. Style the
BasicFigure components to display the image and caption in an aesthetically pleasing manner. Arrange
the BasicFigure components within the FigureList in a grid or list format. Allow users to add or remove
images dynamically. Add hover effects or animations to the images for an interactive experience.

import { useState } from "react";


import { motion } from "framer-motion";

const BasicFigure = ({ src, caption, onRemove }) => {


return (
<motion.div
className="relative rounded-lg overflow-hidden shadow-lg"
whileHover={{ scale: 1.05 }}
>
<img
src={src}
alt={caption}
className="w-full h-64 object-cover rounded-t-lg"
/>
<div className="p-2 bg-white text-center">
<p className="text-sm font-semibold">{caption}</p>
<button
onClick={onRemove}
className="mt-2 text-red-500 text-xs hover:text-red-700"
>
Remove
</button>
</div>
</motion.div>
);
};

const FigureList = () => {


const [figures, setFigures] = useState([
{ id: 1, src: "https://randomuser.me/api/portraits/men/75.jpg", caption: "Placeholder1" },
{ id: 2, src: "https://randomuser.me/api/portraits/men/75.jpg", caption: "Placeholder2" },
]);
const [newImage, setNewImage] = useState("");
const [newCaption, setNewCaption] = useState("");

const addFigure = () => {


if (newImage && newCaption) {
setFigures([...figures, { id: Date.now(), src: newImage, caption: newCaption }]);
setNewImage("");
setNewCaption("");
}
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 12
REACTJS LAB

};

const removeFigure = (id) => {


setFigures(figures.filter((figure) => figure.id !== id));
};

return (
<div className="p-4 max-w-4xl mx-auto">
<div className="mb-4 flex gap-2">
<input
type="text"
placeholder="Image URL"
value={newImage}
onChange={(e) => setNewImage(e.target.value)}
className="p-2 border rounded w-full"
/>
<input
type="text"
placeholder="Caption"
value={newCaption}
onChange={(e) => setNewCaption(e.target.value)}
className="p-2 border rounded w-full"
/>
<button
onClick={addFigure}
className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
>
Add
</button>
</div>
<div className="grid grid-cols-2 md:grid-cols-3 gap-4">
{figures.map((figure) => (
<BasicFigure
key={figure.id}
src={figure.src}
caption={figure.caption}
onRemove={() => removeFigure(figure.id)}
/>
))}
</div>
</div>
);
};
export default function App() {
return (
<div className="min-h-screen bg-gray-100 flex items-center justify-center">
<FigureList />
</div>
);
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 13


REACTJS LAB

OUTPUT :

React App http

ImageURL Caption Add

Placeholder1

Remove

Placeholder2

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 14


REACTJS LAB

PROGRAM 6

Design and implement a React Form that collects user input for name, email, and password. Form
Fields are Name, Email, Password. Ensure all fields are filled before allowing form submission.Validate
the email field to ensure it follows the correct email format (e.g., example@domain.com). Optionally
enforce a minimum password length or complexity. Display error messages for invalid or missing
inputs. Provide visual cues (e.g., red borders) to highlight invalid fields. Prevent form submission until
all fields pass validation. Log or display the entered data upon successful submission (optional). Add a
"Show Password" toggle for the password field. Implement clientside sanitization to ensure clean input.

import React, { useState } from "react";

const Form = () => {


const [formData, setFormData] = useState({ name: "", email: "", password: "" });
const [errors, setErrors] = useState({});
const [showPassword, setShowPassword] = useState(false);

const validateEmail = (email) => {


const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
};

const validateForm = () => {


let newErrors = {};
if (!formData.name.trim()) newErrors.name = "Name is required.";
if (!formData.email.trim()) {
newErrors.email = "Email is required.";
} else if (!validateEmail(formData.email)) {
newErrors.email = "Invalid email format.";
}
if (!formData.password.trim()) {
newErrors.password = "Password is required.";
} else if (formData.password.length < 6) {
newErrors.password = "Password must be at least 6 characters long.";
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};

const handleChange = (e) => {


setFormData({ ...formData, [e.target.name]: e.target.value });
};

const handleSubmit = (e) => {


e.preventDefault();
if (validateForm()) {
console.log("Form Submitted Successfully", formData);
}
};

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 15


REACTJS LAB

return (
<div className="max-w-md mx-auto p-6 bg-white rounded-lg shadow-md">
<h2 className="text-xl font-semibold mb-4">User Registration</h2>
<form onSubmit={handleSubmit}>
<div className="mb-4">
<label className="block mb-1">Name</label>
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
className={`w-full p-2 border ${errors.name ? "border-red-500" : "border-gray-300"}
rounded`}
/>
{errors.name && <p className="text-red-500 text-sm">{errors.name}</p>}
</div>

<div className="mb-4">
<label className="block mb-1">Email</label>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
className={`w-full p-2 border ${errors.email ? "border-red-500" : "border-gray-300"}
rounded`}
/>
{errors.email && <p className="text-red-500 text-sm">{errors.email}</p>}
</div>

<div className="mb-4">
<label className="block mb-1">Password</label>
<div className="relative">
<input
type={showPassword ? "text" : "password"}
name="password"
value={formData.password}
onChange={handleChange}
className={`w-full p-2 border ${errors.password ? "border-red-500" : "border-gray-300"}
rounded`}
/>
<button
type="button"
className="absolute right-2 top-2 text-sm"
onClick={() => setShowPassword(!showPassword)}
>
{showPassword ? "Hide" : "Show"}
</button>
</div>
{errors.password && <p className="text-red-500 text-sm">{errors.password}</p>}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 16


REACTJS LAB

</div>

<button
type="submit"
className="w-full bg-blue-500 text-white p-2 rounded mt-4 hover:bg-blue-600"
>
Submit
</button>
</form>
</div>
);
};

export default Form;

OUTPUT :

User Registration
Name
Email
giri@gmail.com
Password
●●●●●●●● Show
Submit

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 17


REACTJS LAB

PROGRAM 7

Develop a React Application featuring a ProfileCard component to display a user's profile information,
including their name, profile picture, and bio. The component should demonstrate flexibility by
utilizing both external CSS and inline styling for its design. Display the following information: Profile
picture, User's name, A short bio or description Use an external CSS file for overall structure and
primary styles, such as layout, colors, and typography. Apply inline styles for dynamic or specific
styling elements, such as background colors or alignment. Design the ProfileCard to be visually
appealing and responsive. Ensure the profile picture is displayed as a circle, and the name and bio are
appropriately styled. Add hover effects or animations to enhance interactivity. Allow the background
color of the card to change dynamically based on a prop or state.

import React from "react";


import ProfileCard from "./components/ProfileCard";

function App() {
return (
<div className="app">
<ProfileCard
name="John Doe"
bio="Web Developer & Designer | Passionate about UI/UX"
profilePic="https://randomuser.me/api/portraits/men/75.jpg"
initialBgColor="#f3f3f3"
/>
</div>
);
}

export default App;

// ProfileCard.js

import React, { useState } from "react";


import "./ProfileCard.css";

const ProfileCard = ({ name, bio, profilePic, initialBgColor }) => {


const [bgColor, setBgColor] = useState(initialBgColor);

const handleHover = () => {


setBgColor(bgColor === initialBgColor ? "#FFD700" : initialBgColor);
};

return (
<div
className="profile-card"
style={{ backgroundColor: bgColor }}
onMouseEnter={handleHover}
onMouseLeave={handleHover}
>
<img src={profilePic} alt={name} className="profile-pic" />
<h2 className="profile-name">{name}</h2>
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 18
REACTJS LAB

<p className="profile-bio">{bio}</p>
</div>
);
};

export default ProfileCard;

// ProfileCard.css

.profile-card {
width: 300px;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
text-align: center;
transition: background-color 0.3s ease-in-out, transform 0.2s ease-in-out;
}

.profile-card:hover {
transform: scale(1.05);
}

.profile-pic {
width: 100px;
height: 100px;
border-radius: 50%;
object-fit: cover;
margin-bottom: 10px;
}

.profile-name {
font-size: 22px;
color: #333;
margin: 5px 0;
}

.profile-bio {
font-size: 16px;
color: #666;
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 19


REACTJS LAB

OUTPUT :

John Doe
WebDeveloper&Designer|Passionate about
UI/UX

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 20


REACTJS LAB

PROGRAM 8

Develop a Reminder Application that allows users to efficiently manage their tasks. The application
should include the following functionalities: Provide a form where users can add tasks along with due
dates. The form includes task name,Due date,An optional description. Display a list of tasks
dynamically as they are added. Show relevant details like task name, due date, and completion status.
Include a filter option to allow users to view all Tasks and Display all tasks regardless of status. Show
only tasks marked as completed. Show only tasks that are not yet completed.

import { useState } from "react";

export default function ReminderApp() {


const [tasks, setTasks] = useState([]);
const [filter, setFilter] = useState("all");

const addTask = (task) => {


setTasks([...tasks, { ...task, id: Date.now(), completed: false }]);
};

const toggleTaskCompletion = (id) => {


setTasks(
tasks.map((task) =>
task.id === id ? { ...task, completed: !task.completed } : task
)
);
};

const filteredTasks = tasks.filter((task) => {


if (filter === "completed") return task.completed;
if (filter === "pending") return !task.completed;
return true;
});

return (
<div className="p-6 max-w-xl mx-auto bg-white rounded-xl shadow-md space-y-4">
<h1 className="text-2xl font-bold">Reminder Application</h1>
<TaskForm addTask={addTask} />
<Filter setFilter={setFilter} />
<TaskList tasks={filteredTasks} toggleTaskCompletion={toggleTaskCompletion} />
</div>
);
}

function TaskForm({ addTask }) {


const [taskName, setTaskName] = useState("");
const [dueDate, setDueDate] = useState("");
const [description, setDescription] = useState("");

const handleSubmit = (e) => {


e.preventDefault();

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 21


REACTJS LAB

if (!taskName || !dueDate) return;


addTask({ taskName, dueDate, description });
setTaskName("");
setDueDate("");
setDescription("");
};

return (
<form onSubmit={handleSubmit} className="space-y-2">
<input
type="text"
placeholder="Task Name"
className="border p-2 w-full"
value={taskName}
onChange={(e) => setTaskName(e.target.value)}
required
/>
<input
type="date"
className="border p-2 w-full"
value={dueDate}
onChange={(e) => setDueDate(e.target.value)}
required
/>
<textarea
placeholder="Description (Optional)"
className="border p-2 w-full"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<button type="submit" className="bg-blue-500 text-white px-4 py-2 rounded">
Add Task
</button>
</form>
);
}

function TaskList({ tasks, toggleTaskCompletion }) {


return (
<div className="space-y-2">
{tasks.length === 0 ? (
<p className="text-gray-500">No tasks available.</p>
):(
tasks.map((task) => (
<TaskItem key={task.id} task={task} toggleTaskCompletion={toggleTaskCompletion} />
))
)}
</div>
);
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 22


REACTJS LAB

function TaskItem({ task, toggleTaskCompletion }) {


return (
<div className="flex items-center justify-between border p-2 rounded">
<div>
<h3 className={`text-lg ${task.completed ? "line-through text-gray-500" : ""}`}>
{task.taskName}
</h3>
<p className="text-sm text-gray-600">Due: {task.dueDate}</p>
{task.description && <p className="text-sm text-gray-500">{task.description}</p>}
</div>
<button
className={`px-3 py-1 text-white rounded ${task.completed ? "bg-green-500" : "bg-red-
500"}`}
onClick={() => toggleTaskCompletion(task.id)}
>
{task.completed ? "Completed" : "Mark Complete"}
</button>
</div>
);
}
function Filter({ setFilter }) {
return (
<div className="flex space-x-2">
<button className="bg-gray-200 px-3 py-1 rounded" onClick={() => setFilter("all")}>
All
</button>
<button className="bg-green-300 px-3 py-1 rounded" onClick={() => setFilter("completed")}>
Completed
</button>
<button className="bg-yellow-300 px-3 py-1 rounded" onClick={() => setFilter("pending")}>
Pending
</button>
</div>
);
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 23


REACTJS LAB

OUTPUT :

ReminderApplication
Description
TaskName dd/mm/yyyy (Optional) Add Task
AllCompletedPending
codiing
Due: 2025-02-01

coding on reactjs

Mark Complete

reading
Due: 2025-01-30

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 24


REACTJS LAB

PROGRAM 9

Design a React application that demonstrates the implementation of routing using the react-router-dom
library. The application should include the Navigation Menu: Create a navigation bar with links to
three distinct pages, Home, About, Contact. Develop separate components for each page (Home, About,
and Contact) with appropriate content to differentiate them. Configure routes using react-router-dom
to render the corresponding page component based on the selected link. Use BrowserRouter and Route
components for routing. Highlight the active link in the navigation menu to indicate the current page.

import React from "react";


import { BrowserRouter as Router, Routes, Route, NavLink } from "react-router-dom";
import Home from "./Home";
import About from "./About";
import Contact from "./Contact";
import "./App.css"; // Add styles for active link highlighting

const App = () => {


return (
<Router>
<div>
<nav>
<ul>
<li>
<NavLink to="/" className={({ isActive }) => (isActive ? "active" : "")} end>
Home
</NavLink>
</li>
<li>
<NavLink to="/about" className={({ isActive }) => (isActive ? "active" : "")}>
About
</NavLink>
</li>
<li>
<NavLink to="/contact" className={({ isActive }) => (isActive ? "active" : "")}>
Contact
</NavLink>
</li>
</ul>
</nav>

<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</div>
</Router>
);
};

export default App;


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 25
REACTJS LAB

// About.js
import React from "react";

const About = () => {


return <h2>About Us</h2>;
};

export default About;

// Contact.js
import React from "react";

const Contact = () => {


return <h2>Contact Us</h2>;
};

export default Contact;

// Home.js

import React from "react";

const Home = () => {


return <h2>Welcome to the Home Page</h2>;
};

export default Home;

// App.css

nav ul {
display: flex;
list-style-type: none;
gap: 20px;
}

nav ul li a {
text-decoration: none;
color: black;
padding: 5px 10px;
}

nav ul li a.active {
color: white;
background-color: blue;
border-radius: 5px;
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 26


REACTJS LAB

OUTPUT :

Home About Contact

Welcome to the Home Page

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 27


REACTJS LAB

PROGRAM 10

Design a React application featuring a class-based component that demonstrates the use of lifecycle
methods to interact with an external API. The component should fetch and update data dynamically
based on user interactions or state changes. Use the componentDidMount lifecycle method to fetch data
from an API when the component is initially rendered. Display the fetched data in a structured format,
such as a table or list. Use the componentDidUpdate lifecycle method to detect changes in the
component's state or props. Trigger additional API calls to update the displayed data based on user
input or actions (e.g., filtering, searching, or pagination). Implement error handling to manage issues
such as failed API requests or empty data responses. Display appropriate error messages to the user
when necessary. Allow users to perform actions like filtering, searching, or refreshing the data. Reflect
changes in the displayed data based on these interactions.

import React, { Component } from 'react';


import axios from 'axios';

class DataFetcher extends Component {


constructor(props) {
super(props);
this.state = {
data: [],
searchQuery: '',
error: null,
loading: true
};
}

componentDidMount() {
this.fetchData();
}

componentDidUpdate(prevProps, prevState) {
if (prevState.searchQuery !== this.state.searchQuery) {
this.fetchData();
}
}

fetchData = async () => {


this.setState({ loading: true, error: null });
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
const filteredData = response.data.filter(item =>
item.title.toLowerCase().includes(this.state.searchQuery.toLowerCase())
);
this.setState({ data: filteredData, loading: false });
} catch (error) {
this.setState({ error: 'Failed to fetch data', loading: false });
}
};

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 28


REACTJS LAB

handleSearch = (event) => {


this.setState({ searchQuery: event.target.value });
};

handleRefresh = () => {
this.fetchData();
};

render() {
const { data, searchQuery, error, loading } = this.state;

return (
<div>
<h2>Data Fetcher</h2>
<input
type="text"
placeholder="Search..."
value={searchQuery}
onChange={this.handleSearch}
/>
<button onClick={this.handleRefresh}>Refresh</button>
{loading && <p>Loading data...</p>}
{error && <p style={{ color: 'red' }}>{error}</p>}
<ul>
{data.length > 0 ? (
data.map(item => (
<li key={item.id}>{item.title}</li>
))
):(
<p>No data available</p>
)}
</ul>
</div>
);
}
}

export default DataFetcher;

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 29


REACTJS LAB

OUTPUT :

Data Fetcher
Search... Refresh

• suntaut facere repellat providentoccaecati excepturi optio reprehenderit


• qui est esse
• ea molestias quasi exercitationem repellat qui ipsa sit aut
• eum et est occaecati
• nesciuntquas odio
• dolorem eum magni eos aperiam quia
• magnamfacilis autem
• dolorem dolore est ipsam
• nesciunt iure omnis dolorem tempora et accusantium
• optio molestias id quia eum
• etea vero quia laudantium autem
• inquibusdam tempore odit est dolorem
• dolorum ut in voluptas mollitia et saepe quo animi
• voluptatem eligendi optio
• eveniet quod temporibus
• sintsuscipit perspiciatis velit dolorum rerum ipsa laboriosam odio
• fugit voluptas sedmolestias voluptatem provident
• voluptate et itaque vero tempora molestiae
• adipisci placeatillum aut reiciendis qui
• doloribus ad provident suscipit at
• asperiores ea ipsam voluptatibusmodi minima quia sint
• dolor sint quo a velit explicabo quia nam
• maxime id vitae nihil numquam
• autemhic labore sunt dolores incidunt
• rem alias distinctio quo quis

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 30

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy