ReactJS[1]
ReactJS[1]
Experiment – 1
Aim: Installation of NodeJS, ReactJs Libraries, Create ReactJS App, and Run ReactApp
*Install Node.js
• Go to the Node.js website: https://nodejs.org/en/ and download the installer for
your operating system.
• Once the installer is downloaded, run it and follow the on-screen instructions.
• After the installation is complete, open a command prompt and run the following
command to verify that Node.js is installed correctly:
node –v
*Change directory
cd reactjs
*Change directory
cd myapp
*Run App
npm start
Page |2
SOURCE CODE
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>
);
}
App.css
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
.App-header {
background-color: #282c34;
Page |3
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
Index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
Index.css
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI',
'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica
Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier
New',
monospace;
}
Output:
Page |5
Experiment – 2
Aim: Create a function component for displaying Employee details in a table
format using the props.
*Props:
. In React, “props” are inputs to components. They are single values or objects
containing set of values that are passed to components on creation using a naming
convention similar to HTML-tag attributes. The props are then accessed using the dot
notation in the child component e.g., props.name.
*App Component:
. This is the main component of our application. It returns a table with a header and
three rows of employee data. Each row is an Employee component with props for
name, empid, and designation
*Employee Component:
. This component takes in name, empid, and designation as props and returns a
TableRow component with these props.
SOURCE CODE
App.js
import logo from './logo.svg';
import './App.css';
function App() {
return (
<>
<center>
<header />
<table border="1">
<thead style={{color:"red"}}>
<tr>
<th>EMPID</th>
<th>Full Name</th>
<th>Designation</th>
</tr>
</thead>
<Employee name="Krishna" empid="98980"
designation="manager"/>
<Employee name="Rama" empid="98981" designation="Team
Lead"/>
Page |6
);
}
function TableRow(props) {
return (
<tr>
<td>{props.empid}</td>
<td>{props.name}</td>
<td>{props.designation}</td>
</tr>
);
}
function Header() {
return (
<h1 className='style2'>Employee Data</h1>
);
}
App.css
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
Page |7
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.myStyle {
color: blue;
font-size: 70px;
}
Output:
Page |8
Experiment – 3
Aim: Create a Class component for Student and display student details in a
table format using the props.
*Props:
. In React, “props” are inputs to components. They are single values or objects
containing set of values that are passed to components on creation using a naming
convention similar to HTML-tag attributes. The props are then accessed using the dot
notation in the child component e.g., props.name.
*App Component:
. This is the main component of our application. It returns a table with a header and
three rows of student data. Each row is a Student component with props for rollno,
name, branch, and year. The table and its body have inline styles defined in the style1
and style2 variables respectively.
*Student Component:
. This component takes in rollno, name, branch, and year as props and returns a table
row (<tr >) with these values in separate table data (<td>) elements.
SOURCE CODE
App.js
import React from 'react';
import './App.css';
var style1 = {
color: "red"
}
var style2 = {
color: "blue"
}
return (
<>
<center>
<Header />
<table border="1" style={style1}>
Page |9
<thead>
<tr>
<th>Roll No</th>
<th>Name</th>
<th>Branch</th>
<th>Year</th>
</tr>
</thead>
<tbody style={style2}>
<Student id="98980" name="Ram" branch="Mech" year="4"
/>
<Student id="98981" name="Murthy" branch="IT" year="3"
/>
<Student id="98982" name="Raju" branch="CSE" year="2"
/>
</tbody>
</table>
</center>
</>
)
}
}
</tr>
</>
)
}
}
App.css
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.myStyle {
color: blue;
font-size: 35px;
}
P a g e | 11
Output:
P a g e | 12
Experiment – 4
Aim: Create a Stateful Class component for Employee and display the details
using <div> tag.
*Props:
. In React, “props” are inputs to components. They are single values or objects
containing set of values that are passed to components on creation using a naming
convention similar to HTML-tag attributes. The props are then accessed using the dot
notation in the child component e.g., props.name.
*App Component:
. This is the main component of our application. It has a state variable employee
which is an array of objects, each representing an employee with id, name,
designation, and department properties. In the render method, it returns a table with a
header and rows of employee data. Each row is an Employee component with data
prop which is an employee object.
*Employee Component:
. This component takes in data as props and returns a div with employee details.Each
component can maintain its own state, which lives in an object called this.state
SOURCE CODE
App.js
import React from 'react';
return (
<div>
<center>
<Header />
<table border="2">
<tbody>
{this.state.employee.map((emp, i) => <Employee key={i}
data
={emp} />)}
</tbody>
</table>
</center>
</div>
);
}
}
Output:
P a g e | 15
Experiment – 5
Aim: Create a Stateless function component for Student and display the details
along with percentage.
*Props:
. In React, “props” are inputs to components. They are single values or objects
containing set of values that are passed to components on creation using a naming
convention similar to HTML-tag attributes. The props are then accessed using the dot
notation in the child component e.g., props.name.
*App Component:
. This is the main component of our application. It uses the useState hook to create a
state variable students which is an array of objects, each representing a student with
name, branch, rollno, and cgpa properties. In the render method, it returns a table with
a header and rows of student data. Each row is a StudentsList component with
students prop which is the students array.
*StudentsList Component:
. This is a stateless functional component that takes in students as props and maps
over the array to return a TableRow component for each student.
*TableRow Component:
. This is another stateless functional component that takes in data as props and returns
a table row (<tr>) with student details in separate table data (<td>) elements.
SOURCE CODE
App.js
import './App.css';
import React, { useState } from 'react';
rollno: '205E5',
cgpa: '9.9',
},
{
name: 'Raju',
branch: 'CSE',
rollno: '205I8',
cgpa: '10',
},
{
name: 'Elon Musk',
branch: 'ECE',
rollno: '205H1',
cgpa: '9.5',
},
{
name: 'Krishna',
branch: 'CSE',
rollno: '204E0',
cgpa: '9.6',
},
{
name: 'Chay',
branch: 'EEE',
rollno: '204G6',
cgpa: '9.8',
},
{
name: 'Sri',
branch: 'CSE',
rollno: '204E7',
cgpa: '8.8',
},
]);
return (
<div className='container-fluid student-app'>
<div className='column'>
<center>
<h1 className='heading1'>Student Data</h1>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Branch</th>
<th>Rollno</th>
<th>CGPA</th>
P a g e | 17
</tr>
</thead>
<tbody>
<StudentsList students={students} />
</tbody>
</table>
</center>
</div>
</div>
);
}
);
}
</>
)
}
Output:
P a g e | 19
Experiment – 6
Aim: Build a Counter app using the useState hook.
*useState hook:
. To start bringing the counter app to life, import the useState hook from React by typing
“import React { useState } from ‘react’” and the app.css file by typing “import
‘./app.css’”. Declare a function called App and return a div with Counter App in an h1
tag.
SOURCE CODE
App.js
import React, { useState } from "react";
import "./App.css";
const Counter = () => {
// Declare state and initialize it to 0
const [count, setCount] = useState(0);
const handleIncrease = () => {
setCount(count + 1);
};
const handleDecrease = () => {
setCount(count - 1);
};
return (
<div>
<div className="title">
<h1>Counter App</h1>
</div>
<button onClick={handleDecrease}>Decrease</button>
<span>{count}</span>
<button onClick={handleIncrease}>Increase</button>
</div>
);
P a g e | 20
};
export default Counter;
App.css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
h1 {
color: #2ecc71;
}
Output:
P a g e | 21
Experiment – 7
Aim: Implement pagination using the useState, useEffect hooks and Fetching
Data.
• Create your react project: yarn create react-app projectname and install the
required modules: yarn add axios react-paginate and then open your app.js
file.
• We will first import our hooks from the react and also import the required modules.
• Now create a functional component and inside that initialize some state using React
useState hook.
• Now we will create a getData function to load our data from the dummy API using
Axios. This will be an asynchronous function that will fetch 5000 arrays of images from
JSONplaceholder API. Paste the below code inside the functional component.
• Now call that getData method inside React useEffect method.
• Create a method to handle our page click. Paste the below code inside the functional
component.
• Now all you need is to return your data state and ReactPaginate tag which we previously
imported from react-paginate. We also need to pass
• our pageCount state to react paginate pageCount props and handlePageClick method to
onPageChange props.
SOURCE CODE
Pagination.js
useEffect(() => {
getData()
}, [offset])
return (
<div className="App">
{data}
<ReactPaginate
previousLabel={"prev"}
nextLabel={"next"}
breakLabel={"..."}
breakClassName={"break-me"}
pageCount={pageCount}
marginPagesDisplayed={2}
pageRangeDisplayed={5}
P a g e | 23
onPageChange={handlePageClick}
containerClassName={"pagination"}
subContainerClassName={"pages pagination"}
activeClassName={"active"}
/>
</div>
);
}
export default Pagination;
App.css
.pagination {
margin: 15px auto;
display: flex;
list-style: none;
outline: none;
}
.pagination > .active > a{
background-color: #47ccde ;
border-color: #47ccde ;
color: #fff;
}
.pagination > li > a{
border: 1px solid #47ccde ;
padding: 5px 10px;
outline: none;
cursor: pointer;
}
.pagination > .active > a, .pagination > .active > span, .pagination
> .active > a:hover, .pagination > .active > span:hover, .pagination
> .active > a:focus, .pagination > .active > span:focus{
background-color: #47ccde ;
P a g e | 24
border-color: #47ccde;
outline: none ;
}
.pagination > li > a, .pagination > li > span{
color: #47ccde
}
.pagination > li:first-child > a, .pagination > li:first-child >
span, .pagination > li:last-child > a, .pagination > li:last-child >
span{
border-radius: unset
}
Output:
P a g e | 25
Experiment – 8
Aim: Render a form component with validation using the useState hook.
• The useState() returns a list with two-element. first is the state itself, and the second is
the function to update this state.
Source Code:
Validation.js:
import React from 'react';
export default class Validation extends React.Component {
state = {
fields: {},
errors: {}
}
//method to validate values
handleValidation = () => {
let fields = this.state.fields;
let errors = {};
let formIsValid = true;
//Name check if name is empty or not
if (!fields["name"]) {
formIsValid = false;
errors["name"] = "Cannot be empty";
P a g e | 26
}
//name should not contain special char
if (typeof fields["name"] !== "undefined") {
if (!fields["name"].match(/^[a-zA-Z]+$/)) {
formIsValid = false; errors["name"] = "Only
letters";
}
}
//Email should not be empty
if (!fields["email"]) {
formIsValid = false;
errors["email"] = "Cannot be empty";
}
//validating email
if (typeof fields["email"] !== "undefined") {
let lastAtPos = fields["email"].lastIndexOf('@');
let lastDotPos = fields["email"].lastIndexOf('.');
Output:
P a g e | 29
Experiment – 9
Aim: Create a To-do List app using the useState, useEffect and useContext
hooks.
Introduction:
• Hooks were introduced in React 16.8. They allow the use of state and other React
features by using functional components. There are various types of hooks available in
React for example useState, useEffect, and useContext among others. For the To-do
List project, we will only be using the useState hook.
• useState — allows adding of state to a functional component.
• Styled-component on the other hand is a popular library that is used to style react
applications. It allows writing actual CSS in your JavaScript
To-Do App:
• The To Do App that we are going to build will allow a user to add a task to a list of to-
do items. Once the task is added, the user will be able to mark it as completed once it's
done. When you click on a task if it was pending it will be marked as complete by
crossing the task with a line. There will be a count that will be displaying both the
pending and completed tasks.
Source Code:
ToDO.js:
import { useState } from "react";
import styled from "styled-components";
import "./index.css";
const Container = styled.div` display: flex;
align-items: center; flex-direction: column;
`;
const Button = styled.button` display:inline-block;
flex: 1; border: none;
background-color: teal; color: white;
height: 30px; width: 50px; border-radius: 2px; cursor: pointer;
`;
P a g e | 30
else {
//Task is complete, modifying it back to pending,
decrement Complete count
setCompletedTaskCount(completedTaskCount - 1);
} item = { ...task, complete: !task.complete };
} else item = { ...task }; return item;
});
setTodoList(list);
}; return (
<Container>
<div>
<h2>Todo List</h2>
<Text value={input} onInput={(e) =>
setInput(e.target.value)} />
<Button onClick={() => handleClick()}>Add</Button>
<Tasks>
<TaskCount>
<b>Pending Tasks</b> {todoList.length -
completedTaskCount}
</TaskCount>
<TaskCount>
<b>Completed Tasks</b> {completedTaskCount}
</TaskCount>
</Tasks>
<div>
<ul>
{todoList.map((todo) => {
return (
<LIST
complete={todo.complete}
id={todo.id}
P a g e | 32
onClick={() =>
handleComplete(todo.id)} style={{
listStyle: "none",
textDecoration:
todo.complete && "line-through",}}
>
{todo.task}
</LIST>
);
})}
</ul>
</div>
</div>
</Container>
);
};
export default ToDo;
Output:
P a g e | 33
Experiment – 10
Aim: Create a React App using the Nested Components and useContext hook.
Source Code:
NestedComponents.js
import { useState, createContext, useContext } from "react";
const UserContext = createContext();
function NestedComponents() {
const [user, setUser] = useState("Lendi College")
return (
<UserContext.Provider value={user}>
<h1>{`Hello ${user}!`}</h1>
<Component2 />
</UserContext.Provider>
);
}
function Component2() {
return (
<>
<h1>Component 2</h1>
<Component3 />
</>
);
}
function Component3() {
return (
<>
<h1>Component 3</h1>
<Component4 />
P a g e | 34
</>
);
}
function Component4() {
return (
<>
<h1>Component 4</h1>
<Component5 />
</>
);
}
function Component5() {
const user = useContext(UserContext);
return (
<>
<h1>Component 5</h1>
<h2>{`Hello ${user} again!`}</h2>
</>
);
}
export default NestedComponents;
Output:
P a g e | 35
Experiment – 11
Aim: Create a React App to demonstrate how to fetch data by using API call.
Source Code:
Reddit.js
import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";
function Reddit() {
const [posts, setPosts] = useState([]);
useEffect(() => {
async function fetchData() {
const res = await fetch(
"https://www.reddit.com/r/reactjs.json"
);
const json = await res.json();
setPosts(json.data.children.map(c => c.data));
}
fetchData();
}, []);
return (
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
export default Reddit;
Output:
P a g e | 36
Experiment – 12
Aim: Create a React App for tracking the state changes by using useRef hook.
Source Code:
TrackingState.js
function TrackingState() {
const [inputValue, setInputValue] = useState("");
const previousInputValue = useRef("");
useEffect(() => {
previousInputValue.current = inputValue;
}, [inputValue]);
return (
<>
<center>
<br /> <br />
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<h2>Current Value: {inputValue}</h2>
<h2>Previous Value:
{previousInputValue.current}</h2>
P a g e | 37
</center>
</>
);
}
export default TrackingState;
Output:
P a g e | 38
Experiment – 13
Aim: Create a React App for tracking the multiple pieces of the state changes
by using the useReducer and Custom State logic.
Source Code:
ToDos.js
import { useReducer } from "react";
const initialTodos = [
{
id: 1,
title: "Todo 1",
complete: false,
},
{
id: 2,
title: "Todo 2",
complete: false,
},
{
id: 3,
title: "Todo 3",
complete: false,
},
];
function Todos() {
const [todos, dispatch] = useReducer(reducer, initialTodos);
return (
<>
{todos.map((todo) => (
<div key={todo.id}>
<label>
<input
type="checkbox"
checked={todo.complete}
onChange={() => handleComplete(todo)}
/>
{todo.title}
</label>
P a g e | 40
</div>
))}
</>
);
}
Output:
P a g e | 41
Experiment – 14
Aim: Build a Password Generator App using React hooks.
Source Code:
App.js
import React, { useState } from 'react'
import "./App.css"
import { numbers, upperCaseLetters, lowerCaseLetters,
specialCharacters } from './Character'
import { toast, ToastContainer } from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css';
import { COPY_Fail, COPY_SUCCESS } from './message';
if (includeUpperCase) {
characterList = characterList + upperCaseLetters
}
if (includeLowerCase) {
characterList = characterList + lowerCaseLetters
}
if (includeSymbols) {
characterList = characterList + specialCharacters
}
setPassword(createPassword(characterList))
notify("Password is generated successfully", false)
}
}
navigator.clipboard.writeText(password)
}
}
P a g e | 44
return (
<div className="App">
<div className="container">
<div className="generator">
<h2 className="generator__header">
Password Generator
</h2>
<div className="generator__password">
<h3 >{password}</h3>
<button className="copy__btn">
<i onClick={handleCopyPassword} className="far fa-
clipboard"></i>
</button>
</div>
<div className="form-group">
<label htmlFor="password-strength">Password
length</label>
<input className="pw" defaultValue={passwordLength}
onChange={(e) => setPasswordLength(e.target.value)} type="number"
id="password-stregth" name="password-strength" max="26" min="8" />
P a g e | 45
</div>
<div className="form-group">
<label htmlFor="uppercase-letters">Add Uppercase
Letters</label>
<input checked={includeUpperCase} onChange={(e) =>
setIncludeUpperCase(e.target.checked)} type="checkbox"
id="uppercase-letters" name="uppercase-letters" />
</div>
<div className="form-group">
<label htmlFor="lowercase-letters">Add Lowercase
Letters</label>
<input checked={includeLowerCase} onChange={(e) =>
setIncludeLowerCase(e.target.checked)} type="checkbox"
id="lowercase-letters" name="lowercase-letters" />
</div>
<div className="form-group">
<label htmlFor="include-numbers">Include Numbers</label>
<input checked={includeNumbers} onChange={(e) =>
setIncludeNumbers(e.target.checked)} type="checkbox" id="include-
numbers" name="include-numbers" />
</div>
<div className="form-group">
<label htmlFor="include-symbols">Include Symbols</label>
<input checked={includeSymbols} onChange={(e) =>
setIncludeSymbols(e.target.checked)} type="checkbox" id="include-
symbols" name="include-symbols" />
</div>
<button onClick={handleGeneratePassword}
className="generator__btn">
Generate Password
</button>
<ToastContainer
position="top-center"
autoClose={5000}
P a g e | 46
hideProgressBar={false}
newestOnTop={false}
closeOnClick
rtl={false}
pauseOnFocusLoss
draggable
pauseOnHover
/>
</div>
</div>
</div>
)
}
export default App
Character.js
export const numbers = '0123456789'
export const upperCaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
export const lowerCaseLetters ='abcdefghijklmnopqrstuvwxyz'
export const specialCharacters = "!'^+%&/()=?_#$½§{[]}|;:>÷`<.*-@é"
Message.js
export const COPY_SUCCESS = "Password successfully copied to
clipboard"
export const COPY_Fail = "Password successfully copied to clipboard"
P a g e | 47
App.css
.App{
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.generator{
}
P a g e | 48
.form-group{
display: flex;
justify-content: space-between;
color: gre;
margin-bottom: 15px;
}
Output:
P a g e | 49
Experiment – 15
Aim: Build a real-time chat app using the useState and useEffect hooks.
Using the useState hook:
• The first hook we’re going to use is useState. It allows us to maintain state within our
component as opposed to, say, having to write and initialize a class using this.state.
Data that remains constant, such as username, is stored in useState variables. This
ensures the data remains easily available while requiring a lot less code to write.
• The main advantage of useState is that it’s automatically reflected in the rendered
component whenever we update the state of the app. If we were to use regular
variables, they wouldn’t be considered as the state of the component and would have
to be passed as props to re-render the component. So, again, we’re cutting out a lot of
work and streamlining things in the process.
• The hook is built right into React, so we can import it with a single line:
import React,{useState} from ‘react’;
• We are going to create a simple component that returns “Hello” if the user is already
logged in or a login form if the user is logged out. We check the id variable for that.
• Our form submissions will be handled by a function we’re creating called
handleSubmit. It will check if the Name form field is completed. If it is, we will set
the id and room values for that user. Otherwise, we’ll throw in a message reminding
the user that the Name field is required in order to proceed.
Source Code:
App.js
import React, { useState } from 'react'; import './index.css';
export default () => {
const [id, setId] = useState("");
const [nameInput, setNameInput] = useState("");
const [room, setRoom] = useState("");
const handleSubmit = e => {
e.preventDefault();
if (!nameInput) {
return alert("Name can't be empty");
}
P a g e | 50
setId(name);
socket.emit("join", name, room);
};
• That’s how we’re using the useState hook in our chat application. Again, we’re
importing the hook from React, constructing values for the user’s ID and chat
room location, setting those values if the user’s state is logged in, and returning a
login form if the user is logged out.
P a g e | 51
• We are going to use the useEffect hook to run a piece of code only when the
application loads. This ensures that our code only runs once rather than every time
the component re-renders with new data, which is good for performance.
• All we need to do to start using the hook is to import it.
• We will need a component that renders a message or an update
based on the presence or absence of a sende ID in the array. Being
the creative people we are, let’s call that component Messages.
• Let’s put our socket logic inside useEffect so that we don’t duplicate the same set
of messages repeatedly when a component re-renders. We will define our
message hook in the component, connect to the socket, then set up listeners for
new messages and updates in the useEffect hook itself. We will also set up
update functions inside the listeners.
Code:
</ul>
<ul id="online">
{" "}
🌐 : <Online data={online} />{" "}
</ul>
<div id="sendform">
<form onSubmit={e => handleSend(e)} style={{ display: "flex" }}>
<input id="m" onChange={e => setInput(e.target.value.trim())} />
<button style={{ width: "75px" }} type="submit"> Send
</button>
</form>
</div>
</section>
) : (
Output: