REACT JS - FULL STACK DEVELOPEMENT
1. Create a simple React component called Counter that displays a number and has two buttons: "Increment" and "Decrement." The number should start at 0 and change when the buttons are clicked.
a. -Use state to manage the number.
b. -Pass the initial number as a prop to the Counter component.
Solution - Paste The Following Counter.jsx And App.js In src Folder.
// >>>COUNTER.JS
import React, { useState } from 'react';
const Counter = ({ initialNumber }) => {
const [count, setCount] = useState(initialNumber || 0);
const handleIncrement = () => {
setCount(count + 1);
};
const handleDecrement = () => {
setCount(count - 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={handleIncrement}>Increment</button>
<button onClick={handleDecrement}>Decrement</button>
</div>
);
};
export default Counter;
//>>>APP.JS
import React from 'react';
import Counter from './Counter.js'; // Make sure to adjust the path based on your file structure
const App = () => {
return (
<div>
<h1>Counter</h1>
<Counter initialNumber={0} />
</div>
);
};
export default App;
2. Build a multi-page React application that includes two pages: "Home" and "About."
a. Create a navigation bar with links to the "Home" and "About" pages.
b. Implement routing using a library like React Router.
c. Each page should have a unique URL and content(any).
Solution - Create A Folder Named "components" And In components Folder Add Two JSX Files( About.jsx And Home.jsx)
// components/About.js
import React from 'react';
const About = () => {
return (
<div>
<h2>About Page</h2>
<p>This is the About Page with some information about the application.</p>
</div>
);
};
export default About;
// components/Home.js
import React from 'react';
const Home = () => {
return (
<div>
<h2>Home Page</h2>
<p>Welcome to the Home Page!</p>
</div>
);
};
export default Home;
// App.js
import React from 'react';
import { BrowserRouter as Router, Route, Link, Routes } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
const App = () => {
return (
<Router>
<div>
<h1>Multi-Page React</h1>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav>
<hr />
<Routes>
<Route path="/about" element={<About />} />
<Route path="/" element={<Home />} />
</Routes>
</div>
</Router>
);
};
export default App;
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
3. Create a basic todo list application: (use useState() )
a. Build a component for adding, displaying, and deleting tasks.
b. Use state to manage the list of tasks.
c. Add a form for users to input new tasks.
d. Display the list of tasks and provide a button to remove them.
e. Add a counter for the total number of tasks.
import React, { useState } from 'react';
const TodoApp = () => {
// State to manage the list of tasks
const [tasks, setTasks] = useState([]);
// State to manage the input value for new tasks
const [newTask, setNewTask] = useState('');
// Function to handle adding a new task
const addTask = () => {
if (newTask.trim() !== '') {
setTasks([...tasks, { text: newTask, completed: false }]);
setNewTask('');
}
};
// Function to handle removing a task
const removeTask = (index) => {
const updatedTasks = [...tasks];
updatedTasks.splice(index, 1);
setTasks(updatedTasks);
};
// Function to handle toggling the completion status of a task
const toggleComplete = (index) => {
const updatedTasks = [...tasks];
updatedTasks[index].completed = !updatedTasks[index].completed;
setTasks(updatedTasks);
};
// Function to handle adding a new task when "Enter" key is pressed
const handleKeyPress = (e) => {
if (e.key === 'Enter') {
addTask();
}
};
return (
<div>
<h1>Slip 3</h1>
<h2>Todo List</h2>
{/* Form to input new tasks */}
<div>
<input
type="text"
value={newTask}
onChange={(e) => setNewTask(e.target.value)}
onKeyPress={handleKeyPress}
placeholder="Enter a new task"
/>
<button onClick={addTask}>Add Task</button>
</div>
{/* Display the list of tasks */}
<ul>
{tasks.map((task, index) => (
<li
key={index}
style={{ textDecoration: task.completed ? 'line-through' : 'none' }}
onClick={() => toggleComplete(index)}
>
{task.text}
<button onClick={(e) => { e.stopPropagation(); removeTask(index); }}>
<span role="img" aria-label="trash">🗑️</span>
</button>
</li>
))}
</ul>
{/* Display the total number of tasks */}
<p>Total Tasks: {tasks.length}</p>
</div>
);
};
export default TodoApp;
4. Create two components ParentComponent ChildComponent
a. ParentComponent passes prop as name to ChildComponent
b. ChildComponent Displays name e.g. “ Hi <name> ”
Solution - Create A Folder Named “ParentComponent” In src folder and inside ParentComponent create folder “ChildComponent” Paste ParentComponent.jsx in ParentComponent Folder
// ParentComponent.jsx
import React from 'react';
import ChildComponent from './ChildComponent/ChildComponent';
const ParentComponent = () => {
const name = 'Ibram'; // You can change this value
return (
<div>
{/* <h1>Parent Component</h1> */}
<ChildComponent name={name} />
</div>
);
};
export default ParentComponent;
// ChildComponent.jsx
import React from 'react';
const ChildComponent = (props) => {
return (
<div>
{/* <h2>Child Component</h2> */}
<p>Hi {props.name}</p>
</div>
);
};
export default ChildComponent;
// src/App.js
import React from 'react';
import ParentComponent from './ParentComponent/ParentComponent';
const App = () => {
return (
<div>
<h1>Displaying Name Using Components</h1>
<ParentComponent />
</div>
);
};
export default App;
5. Print below array elements using map into the screen
a. const weekDays = [“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”]
import React from 'react';
const WeekDaysList = () => {
const weekDays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
return (
<div>
<h1>Array Printing Using Map</h1>
<h2>Week Days</h2>
<ul>
{weekDays.map((day, index) => (
<li key={index}>{day}</li>
))}
</ul>
</div>
);
};
export default WeekDaysList;
6. Create two components ParentComponent, ChildComponent
a. ParentComponent passes prop as name to ChildComponent
b. ChildComponent Displays converting name to uppercase and print
c. E.g ParentComponent passes John ChildComponent prints My name is JOHN
Create A Folder Named “components” In src folder and inside components. Create two folders named “ParentComponent” And “ChildComponent” Paste ParentComponent.jsx in ParentComponent Folder
// ParentComponent.jsx
import React from 'react';
import ChildComponent from '../ChildComponent/ChildComponent';
const ParentComponent = () => {
const name = 'John'; // You can change this value
return (
<div>
{/* <h1>Parent Component</h1> */}
<ChildComponent name={name} />
</div>
);
};
export default ParentComponent;
// ChildComponent.jsx
import React from 'react';
const ChildComponent = (props) => {
const uppercaseName = props.name.toUpperCase();
return (
<div>
{/* <h2>Child Component</h2> */}
<p>My name is {uppercaseName}</p>
</div>
);
};
export default ChildComponent;
// App.js
import React from 'react';
import ParentComponent from './components/ParentComponent/ParentComponent';
function App() {
return (
<div className="App">
<h1>Name Display Using Components</h1>
<ParentComponent />
</div>
);
}
export default App;
7. Implement useEffect hook and print all three lifecycle state
import React, { useState, useEffect } from 'react';
const LifecycleExample = () => {
// Mounting
useEffect(() => {
console.log('Inside mount');
// Cleanup function (will be called on unmount)
return () => {
console.log('Inside unmount');
};
}, []);
// Updating
useEffect(() => {
console.log('Inside update');
// Cleanup function (will be called on update and unmount)
return () => {
console.log('Inside unmount (from update)');
};
});
// State for updating
const [count, setCount] = useState(0);
return (
<div>
<h1>Slip 7</h1>
<h2>Lifecycle Example</h2>
<p>Current Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase Count</button>
</div>
);
};
export default LifecycleExample;
8. Print below array elements using map into the screen.
a. const fruits = ["apple", "banana", "cherry", “bat”]
b. Only print fruits it should remove bat and print it.
import React from 'react';
const FruitsList = () => {
const fruits = ["apple", "banana", "cherry", "bat"];
// Filter out "bat" from the fruits array
const filteredFruits = fruits.filter(fruit => fruit !== "bat");
return (
<div>
<h1>FILTER "BAT" USING MAP</h1>
<h2>Fruits List</h2>
<ul>
{filteredFruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
</div>
);
};
export default FruitsList;
9. Print below array elements using map into the screen.
a. let fruits1 = ["apple", "banana"];
b. let fruits2 = ["cherry", "orange"];
c. Merge both fruits array and print it.
import React from 'react';
const FruitsList = () => {
let fruits1 = ["apple", "banana"];
let fruits2 = ["cherry", "orange"];
// Merge both arrays
let allFruits = [...fruits1, ...fruits2];
return (
<div>
<h1>MAP</h1>
<h2>Merged Fruits List</h2>
<ul>
{allFruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
</div>
);
};
export default FruitsList;
10. Create a basic todo list application: (use useReducer() )
a. Build a component for adding, displaying, and deleting tasks.
b. Use state to manage the list of tasks.
c. Add a form for users to input new tasks.
d. Display the list of tasks and provide a button to remove them.
e. Add a counter for the total number of tasks.
import React, { useState, useReducer } from 'react';
// Action types
const ADD_TASK = 'ADD_TASK';
const REMOVE_TASK = 'REMOVE_TASK';
const TOGGLE_COMPLETE = 'TOGGLE_COMPLETE';
// Reducer function
const todoReducer = (state, action) => {
switch (action.type) {
case ADD_TASK:
return [...state, { text: action.payload, completed: false }];
case REMOVE_TASK:
const updatedTasks = [...state];
updatedTasks.splice(action.payload, 1);
return updatedTasks;
case TOGGLE_COMPLETE:
return state.map((task, index) =>
index === action.payload ? { ...task, completed: !task.completed } : task
);
default:
return state;
}
};
const TodoApp = () => {
// State and dispatch using useReducer
const [tasks, dispatch] = useReducer(todoReducer, []);
// State to manage the input value for new tasks
const [newTask, setNewTask] = useState('');
// Function to handle adding a new task
const addTask = () => {
if (newTask.trim() !== '') {
dispatch({ type: ADD_TASK, payload: newTask });
setNewTask('');
}
};
// Function to handle removing a task
const removeTask = (index) => {
dispatch({ type: REMOVE_TASK, payload: index });
};
// Function to handle toggling the completion status of a task
const toggleComplete = (index) => {
dispatch({ type: TOGGLE_COMPLETE, payload: index });
};
// Function to handle adding a new task when "Enter" key is pressed
const handleKeyPress = (e) => {
if (e.key === 'Enter') {
addTask();
}
};
return (
<div>
<h1>Todo App Using useReducer</h1>
<h2>Todo List</h2>
{/* Form to input new tasks */}
<div>
<input
type="text"
value={newTask}
onChange={(e) => setNewTask(e.target.value)}
onKeyPress={handleKeyPress}
placeholder="Enter a new task"
/>
<button onClick={addTask}>Add Task</button>
</div>
{/* Display the list of tasks */}
<ul>
{tasks.map((task, index) => (
<li
key={index}
style={{ textDecoration: task.completed ? 'line-through' : 'none' }}
onClick={() => toggleComplete(index)}
>
{task.text}
<button onClick={(e) => { e.stopPropagation(); removeTask(index); }}>
<span role="img" aria-label="trash">🗑️</span>
</button>
</li>
))}
</ul>
{/* Display the total number of tasks */}
<p>Total Tasks: {tasks.length}</p>
</div>
);
};
export default TodoApp;
11. Design login form which accepts username and password(Two text box) and submit button.
a. On submit button click it should validate username and password and console log if its valid
b. Validity check should be simple like username: Admin & password: Pass123
c. If any other credentials it should say unauthorized.
import React, { useState } from 'react';
const LoginForm = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleLogin = () => {
// Simple validation for username and password
if (username === 'Admin' && password === 'Pass123') {
console.log('Login successful!');
} else {
console.log('Unauthorized. Please check your credentials.');
}
};
return (
<div>
<h1>LOGIN FORM USING REACT</h1>
<h2>Login Form</h2>
<form
onSubmit={(e) => {
e.preventDefault();
handleLogin();
}}
>
<label>
Username:
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</label>
<br />
<label>
Password:
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</label>
<br />
<button type="submit">Submit</button>
</form>
</div>
);
};
export default LoginForm;