React Lab Manual
React Lab Manual
REACT
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.
App.js
import { useState } from "react";
function ControlledInput() {
const [text, setText] = useState("");
return (
<div>
<input type="text" value={text} onChange={handleChange} />
<p>You typed: {text}</p>
</div>
);
}
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.
Footer.js
function Footer(props)
{
<div>
<p>Name :{props.tagline}</p>
</div>
}
export default Footer
Header.js
function Header(props)
BCSL657B REACT
{
<div>
<p>Name :{props.title}</p>
</div>
}
export default Header
Student.js
function Student(props)
{
<div>
<p>Name :{props.name}</p>
</div>
}
export default Student
App.js
return (
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h1>Counter Application</h1>
<input
type="number"
value={step}
onChange={handleStepChange}
min="1"
/>
</div>
</div>
);
};
function Todoform()
{
const[tasks,settasks]=useState(["eat breakfast", "Run", "study"]);
const[newTask,setNewTask]=useState("");
function handleinputchange(event)
{
setNewTask(event.target.value);
}
function todoinput()
{
settasks(t=>[...t,newTask]);
setNewTask("");
}
function deleteTask(index)
{
const updatedTasks=tasks.filter((element,i)=>i!==index);
settasks(updatedTasks);
}
return(
<div className="To-do-list">
<h1> ToDo LIST </h1>
<div>
<input type="text"
placeholder="what is the task today "
BCSL657B REACT
value={newTask}
onChange={handleinputchange}
/>
<button className="add-button"
onClick= {()=>todoinput()}>
ADD
</button>
</div>
<ol>
{tasks.map((task, index) =>
<li key={index}>
<span className="text"> {task}</span>
<button
className="delete-button "
onClick={()=> deleteTask(index)}>
DELETE
</button>
</li>
)}
</ol>
</div>);
}
export default Todoform
App.js
import './App.css';
import Todoform from './Todoform';
function App() {
return (
<div className="App">
<Todoform> </Todoform>
</div>
BCSL657B REACT
);
}
// Remove a figure by id
BCSL657B REACT
return (
<div className="figure-list">
<button className="add-btn" onClick={addFigure}>
Add Image
</button>
<div className="figure-grid">
{figures.map((figure) => (
<BasicFigure
key={figure.id}
imageUrl={figure.imageUrl}
caption={figure.caption}
onDelete={() => removeFigure(figure.id)}
/>
))}
</div>
</div>
);
};
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., [email protected]). 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.
App.js
import React, { useState } from "react";
import "./App.css";
BCSL657B REACT
// Name validation
if (!formData.name) {
newErrors.name = "Name is required";
}
// Email validation
const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
if (!formData.email) {
newErrors.email = "Email is required";
} else if (!emailPattern.test(formData.email)) {
newErrors.email = "Please enter a valid email address";
}
setErrors(newErrors);
return (
<div className="form-container">
<h1>React Registration Form</h1>
<form onSubmit={handleSubmit} className="form">
{/* Name Input */}
<div className={`form-group ${errors.name ? "error" : ""}`}>
<label htmlFor="name">Name</label>
<input
type="text"
id="name"
name="name"
value={formData.name}
onChange={handleInputChange}
className={errors.name ? "input-error" : ""}
/>
BCSL657B REACT
App.css
/* General styling */
body {
font-family: Arial, sans-serif;
background-color: #f4f7f6;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
}
.form-container {
background: white;
padding: 20px 30px;
border-radius: 8px;
box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
width: 100%;
max-width: 400px;
}
h1 {
text-align: center;
color: #333;
}
/* Form styling */
.form {
display: flex;
flex-direction: column;
}
.form-group {
margin-bottom: 15px;
}
label {
font-weight: bold;
margin-bottom: 5px;
color: #333;
}
input {
width: 100%;
BCSL657B REACT
padding: 10px;
font-size: 16px;
border: 1px solid #ddd;
border-radius: 5px;
}
input:focus {
border-color: #4CAF50;
}
.error {
border: 1px solid red;
}
.input-error {
border: 1px solid red;
}
.error-message {
color: red;
font-size: 12px;
margin-top: 5px;
}
.show-password-btn {
background: none;
border: none;
color: #4CAF50;
cursor: pointer;
font-size: 14px;
text-align: right;
margin-top: 5px;
}
.submit-btn {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}
.submit-btn:hover {
background-color: #45a049;
}
BCSL657B REACT
return (
<div className="profile-card"
style={cardStyle}>
<img className="profile-pic"
src={profilePic} alt={`${name}'s profile`} />
<h2 className="profile-
name">{name}</h2>
<p className="profile-bio">{bio}</p>
</div>
);
};
.profile-card:hover {
transform: scale(1.05);
}
.profile-pic {
width: 100px;
BCSL657B REACT
height: 100px;
border-radius: 50%;
object-fit: cover;
border: 3px solid #fff;
}
.profile-name {
font-size: 1.5em;
margin: 10px 0;
color: #333;
}
.profile-bio {
font-size: 1em;
color: #666;
}
App.js
import React from "react";
import Profilecard from "./ProfileCard";
function App() {
return (
<div style={{display: "flex",
justifyContent: "center", marginTop: "50px"
}}>
<Profilecard
name="John Doe"
bio="Web Developer & Tech
Enthusiast"
profilePic="https://via.placeholder.co
m/100"
bgColor="#e3f2fd"
/>
BCSL657B REACT
</div>
);
}
function App() {
const [tasks, setTasks] = useState([]);
const [completedTasks, setCompletedTasks] = useState([]);
const [task, setTask] = useState("");
const [priority, setPriority] = useState("top");
const [deadline, setDeadline] = useState("");
const newTask = {
id: tasks.length + 1,
task,
priority,
deadline,
done: false,
};
setTasks([...tasks, newTask]);
setTask("");
setPriority("top");
setDeadline("");
};
return (
<div className="App">
<header>
<h1>Task Scheduler</h1>
</header>
<main>
<div className="task-form">
<input
type="text"
id="task"
placeholder="Enter task..."
value={task}
onChange={handleTaskChange}
/>
BCSL657B REACT
<select
id="priority"
value={priority}
onChange={handlePriorityChange}
>
<option value="top">Top Priority</option>
<option value="middle">Middle Priority</option>
<option value="low">Less Priority</option>
</select>
<input
type="date"
id="deadline"
value={deadline}
onChange={handleDeadlineChange}
/>
<button id="add-task" onClick={addTask}>
Add Task
</button>
</div>
<h2 className="heading">Upcoming Tasks</h2>
<div className="task-list" id="task-list">
<table>
<thead>
<tr>
<th>Task Name</th>
<th>Priority</th>
<th>Deadline</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{upcomingTasks.map((t) => (
<tr key={t.id}>
<td>{t.task}</td>
<td>{t.priority}</td>
<td>{t.deadline}</td>
<td>
{!t.done && (
<button
className="mark-done"
onClick={() => markDone(t.id)}
>
Mark Done
</button>
)}
</td>
</tr>
))}
</tbody>
BCSL657B REACT
</table>
</div>
<div className="completed-task-list">
<h2 className="cheading">Completed Tasks</h2>
<table>
<thead>
<tr>
<th>Task Name</th>
<th>Priority</th>
<th>Deadline</th>
</tr>
</thead>
<tbody>
{completedTasks.map((ct) => (
<tr key={ct.id}>
<td>{ct.task}</td>
<td>{ct.priority}</td>
<td>{ct.deadline}</td>
</tr>
))}
</tbody>
</table>
</div>
</main>
</div>
);
}
)
}
Contact.js
import Header from '../Components/Header'
export default function()
{
return(
<>
<Header />
<h2> Contact </h2></>
)
}
Home.js
export default function()
{
return(
)
}
App.js
import { BrowserRouter,Routes,Route } from 'react-router-dom';
import Home from './Pages/Home';
import Contact from './Pages/Contact';
import About from './Pages/About';
import './App.css';
</BrowserRouter>
</div>
);
}
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.
App.js
import logo from './logo.svg';
import './App.css';
componentDidMount() {
this.fetchData();
}
componentDidUpdate(prevProps, prevState) {
// Trigger additional API calls or data processing based on state changes
if (prevState.filterQuery !== this.state.filterQuery) {
this.applyFilter();
}
}
applyFilter = () => {
const { data, filterQuery } = this.state;
const filteredData = data.filter((item) =>
item.name.toLowerCase().includes(filterQuery.toLowerCase())
);
this.setState({ filteredData });
};
render() {
const { filteredData, isLoading, error, filterQuery } = this.state;
return (
<div>
<h1>Data Fetcher</h1>
<input
type="text"
placeholder="Filter by name"
value={filterQuery}
BCSL657B REACT
onChange={this.handleFilterChange}
/>
{isLoading && <p>Loading data...</p>}
{error && <p>Error: {error}</p>}
{!isLoading && !error && (
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{filteredData.map((item) => (
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.name}</td>
</tr>
))}
</tbody>
</table>
)}
</div>
);
}
}