0% found this document useful (0 votes)
40 views

Labreact

The document contains code for a React BMI calculator app that allows users to enter their height and weight to calculate their BMI. It uses useState hooks to manage state for the input values, calculated BMI, and message to display based on the BMI range. The calculateBMI function calculates BMI based on the inputs and updates the state variables to display the results.

Uploaded by

Pranav Jadhav
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Labreact

The document contains code for a React BMI calculator app that allows users to enter their height and weight to calculate their BMI. It uses useState hooks to manage state for the input values, calculated BMI, and message to display based on the BMI range. The calculateBMI function calculates BMI based on the inputs and updates the state variables to display the results.

Uploaded by

Pranav Jadhav
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

1. App.

js
2. import React from 'react'
3. import { useState } from 'react'
4. import './App.css'
5.
6. const App = () => {
7. const [heightValue, setHeightValue] = useState('');
8. const [weightValue, setWeightValue] = useState('');
9. const [bmiValue, setBmiValue] = useState('');
10. const [bmiMessage, setBmiMessage] = useState('');
11. const calculateBmi = () => {
12. if (heightValue && weightValue) {
13. const heightInMeters = heightValue / 100;
14. const bmi = (weightValue / (heightInMeters *
heightInMeters)).toFixed(2);
15. setBmiValue(bmi);
16.
17. let message = '';
18. if (bmi < 18.5) {
19. message = 'You are Underweight';
20. } else if (bmi >= 18.5 && bmi < 25) {
21. message = 'You are Normal weight';
22. } else if (bmi >= 25 && bmi < 30) {
23. message = 'You are Overweight';
24. } else {
25. message = 'You are Obese';
26. }
27. setBmiMessage(message);
28. } else {
29. setBmiValue('');
30. setBmiMessage('');
31. }
32. };
33. return (
34. <div className="container">
35. <h1>BMI Calculator</h1>
36. <div className="input-container">
37. <label htmlFor="height">Enter Your Height (cm):</label>
38. <input
39. type="number"
40. id="height"
41. value={heightValue}
42. onChange={(e) => setHeightValue(e.target.value)}
43. />
44. </div>
45. <div className="input-container">
46. <label htmlFor="weight">Enter Your Weight (kg):</label>
47. <input
48. type="number"
49. id="weight"
50. value={weightValue}
51. onChange={(e) => setWeightValue(e.target.value)}
52. />
53. </div>
54. <button className="calculate-btn" onClick={calculateBmi}>
55. Click to Calculate BMI
56. </button>
57. {bmiValue && bmiMessage && (
58. <div className="result">
59. <p>
60. Your BMI: <span className="bmi-
value">{bmiValue}</span>
61. </p>
62. <p>
63. Result: <span className="bmi-
message">{bmiMessage}</span>
64. </p>
65. </div>
66. )}
67. </div>
68. )
69.}
70.
71.export default App

App.css
72..App {
73. text-align: center;
74.}
75.
76..App-logo {
77. height: 40vmin;
78. pointer-events: none;
79.}
80.
81.@media (prefers-reduced-motion: no-preference) {
82. .App-logo {
83. animation: App-logo-spin infinite 20s linear;
84. }
85.}
86.
87..App-header {
88. background-color: #282c34;
89. min-height: 100vh;
90. display: flex;
91. flex-direction: column;
92. align-items: center;
93. justify-content: center;
94. font-size: calc(10px + 2vmin);
95. color: white;
96.}
97.
98..App-link {
99. color: #61dafb;
100. }
101.
102. @keyframes App-logo-spin {
103. from {
104. transform: rotate(0deg);
105. }
106. to {
107. transform: rotate(360deg);
108. }
109. }
110.
111. /* App.cs */
112. .container {
113. max-width: 400px;
114. margin: 0 auto;
115. padding: 20px;
116. }
117.
118. h1 {
119. color: #1eff00f3;
120. text-align: center;
121. margin-bottom: 20px;
122. }
123.
124. .input-container {
125. margin-bottom: 10px;
126. }
127.
128. label {
129. display: block;
130. font-weight: bold;
131. margin-bottom: 5px;
132. }
133.
134. input[type='number'] {
135. width: 100%;
136. padding: 10px;
137. font-size: 16px;
138. }
139.
140. .calculate-btn {
141. display: block;
142. width: 100%;
143. padding: 10px;
144. background-color: #007bff;
145. color: #fff;
146. font-size: 16px;
147. border: none;
148. border-radius: 4px;
149. cursor: pointer;
150. }
151.
152. .result {
153. margin-top: 20px;
154. padding: 10px;
155. background-color: #f0f0f0;
156. border-radius: 4px;
157. }
158.
159. .bmi-value {
160. font-weight: bold;
161. }

162. .bmi-message {
163. color: #007bff;
164. font-weight: bold;
}

2.

import React from 'react'


import { useState } from "react";

const App = () => {


const [input, setInput] = useState("");
const [robotList, setRobotList] = useState([]);

const onSubmit = (e) => {


e.preventDefault(); // prevents page refresh
setRobotList([...robotList, input]);
setInput("");
};
return (
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
padding: 20,
}}
>
<form onSubmit={onSubmit}>
<input
value={input}
placeholder={"Generate Robot"}
type="text"
onChange={(e) => setInput(e.target.value)}
/>
</form>
<h2>Robot List</h2>
<div style={{ display: "flex", flexDirection: "row", flexWrap:
"wrap" }}>
{robotList.map((robo) => (
<img
onClick={() => setRobotList(robotList.filter((r) => r !== robo))}
width={200}
height={200}
src={`https://robohash.org/${robo}`}
></img>
))}
</div>
</div>

)
}

export default App

3.

import React, { useContext, useEffect, useState } from "react";

const UsersContext = React.createContext();

function App() {
const [userState, setUserState] = useState({
Bob: true,
Gary: true,
Jessica: true,
Sam: true,
Eric: true,
});

return (
<UsersContext.Provider value={{ userState, setUserState }}>
<UserList />
</UsersContext.Provider>
);
}

const UserList = () => {


const { userState, setUserState } = useContext(UsersContext);

// Function to toggle the online status of a random user


const toggleRandomUserStatus = () => {
const users = Object.keys(userState);
const randomUser = users[Math.floor(Math.random() * users.length)];

setUserState(prevState => ({
...prevState,
[randomUser]: !prevState[randomUser],
}));
};

useEffect(() => {
// Change the status of a random user every two seconds
const intervalId = setInterval(toggleRandomUserStatus, 2000);

return () => {
clearInterval(intervalId);
};
}, []);

return (
<div>
<h2>User List</h2>
<ul>
{Object.entries(userState).map(([userName, isOnline]) => (
<li key={userName}>

{userName} - {isOnline ? '🟢' : '🔴'}


</li>
))}
</ul>
</div>
);
};

export default App;

4.
import { useState } from "react";
import _ from "lodash";
const INITIAL_LIST = {
"Organize closet": [
{ "Donate old clothes and shoes": false },
{ "Buy new shelf": false },
{ "Put in shelf by color": false },
],
"Finish homework": [
{ "Finish math homework": false },
{ "Finish science homework": false },
{ "Finish Reactjs homework": false },
],
"Achieve nirvana": [
{ "Meditate a little": false },
{ "Gain some wisdom": false },
],
};
function App() {
return <Checklist />
}

const Checklist = () => {


const [list, setList] = useState(INITIAL_LIST);

const clickTask = (topTask, index, taskText) => {


const newList = _.cloneDeep(list);
newList[topTask][index][taskText] = !newList[topTask][index][taskText];
setList(newList);

// YOUR CODE HERE


}
// (PROBABLY) MORE OF YOUR CODE HERE
return (
<div
style={{
diplay: "flex",
flexDirection: "column",
alignItems: "center",
padding: 40,
}}
>
{Object.entries(list).map(([topTask, subTasks]) => {
return (
<>
<h2>{topTask}</h2>
<div style={{ display: "flex" }}>
<DisplaySubtasks
topTask={topTask}
subTasks={subTasks}
clickTask={clickTask}
/>
</div>
</>
);
})}
</div>
);
};

const DisplaySubtasks = ({ topTask, subTasks, clickTask }) => {


return (
<>
<div
style={{
display: "flex",
flexDirection: "column",
paddingRight: 50,
width: 250,
}}
>
<h3>Not yet completed</h3>
{subTasks.map((subTask, index) => {
const taskText = Object.keys(subTask)[0];
if (!subTask[taskText])
return (
<p onClick={() => clickTask(topTask, index, taskText)}>
{taskText}
</p>
);
})}
</div>
<div style={{ display: "flex", flexDirection: "column" }}>
<h3>Completed</h3>
{subTasks.map((subTask, index) => {
const taskText = Object.keys(subTask)[0];
if (subTask[taskText])
return (
<p onClick={() => clickTask(topTask, index, taskText)}>
{taskText}
</p>
);
})}
</div>
</>
);
};

export default App

5.

import React, { useState } from "react";

const QUESTIONS = [
{
question: "What is 2*(4+4)?",
answers: ["2", "4", "8", "16"],
correct: 3,
},
{
question: "What is 9*9?",
answers: ["18", "81", "80", "79"],
correct: 1,
},
{
question: "Who was the first president of the United States?",
answers: [
"George Washington",
"John Adams",
"John Quincy Adams",
"Thomas Jefferson",
],
correct: 0,
},
{
question: "What state is Philadelphia in?",
answers: [
"Commonwealth of Pennsylvania",
"New Jersey",
"New York",
"Massachusetts",
],
correct: 0,
},
{
question: "What are the two major political parties in the United
States?",
answers: [
"Democratic Party & Republican Party",
"Green Party & Red Party",
"Bull Party & Moose Party",
"Hamilton Party & Burr Party",
],
correct: 0,
},
];

function App() {
return <Quiz questions={QUESTIONS} />
}

const Quiz = ({ questions }) => {


//Your Code Here
const [score, setScore] = useState(0);
const [currentQuestion, setCurrentQuestion] = useState(0);

const handleAnswer = (currentQuestion, index) => {


if (questions[currentQuestion].correct === index) {
setScore(score + 1);
}
setCurrentQuestion(currentQuestion + 1);
};
return (
<div style={{ margin: "auto", width: "30%" }}>
{currentQuestion < questions.length && (
<>
<h3>{questions[currentQuestion].question}</h3>
{questions[currentQuestion].answers.map((answer, index) => (
<p onClick={() => handleAnswer(currentQuestion, index)}>{answer}</p>
))}
</>
)}
{currentQuestion >= questions.length && (
<p>{`You scored ${(score / questions.length) * 100}%`}</p>
)}
</div>
);
};

export default App

6.

import React from 'react'

function App() {
const ARRAY = [1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 5, 3, 5, 7, 4, 2];
return <DivideBeforeConquer array={ARRAY} />;

}
const DivideBeforeConquer = ({ array }) => {
const middle = Math.floor(array.length / 2);
const slice1 = array.slice(0, middle);
const slice2 = array.slice(middle);

const centeredRow = {
display: "flex",
fontSize: 30,
justifyContent: "center",
};
const centerdColumn = {
display: "flex",
flexDirection: "column",
alignItems: "center",
paddingRight: 5,
paddingLeft: 5,
};

return (
<>
<p style={centeredRow}>{`[${array.toString()}]`}</p>
{array.length !== 1 && (
<div style={centeredRow}>
<div style={centerdColumn}>
<DivideBeforeConquer array={slice1} />
</div>
<div style={centerdColumn}>
<DivideBeforeConquer array={slice2} />
</div>
</div>
)}
</>
);
};

export default App

7.

import React, { useState } from "react";

function App() {
return (
<div
style={{
display: "flex",
justifyContent: "center",
paddingTop: 20,
}}
>
<ValidatedForm />
</div>
);
}

const ValidatedForm = () => {


const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [accounts, setAccounts] = useState([
{ username: "SonaSalem1", password: "1234567" },
]);
const userExists = (user, pass) => {
for (const account of accounts) {
if (account.username === user && account.password === pass) {
return true;
}
}
return false;
};
const onSubmit = (e) => {
e.preventDefault(); // prevents page refresh
if (userExists(username, password)) {
alert("Successfully logged in.");
} else {
alert("Incorrect username or password.");
}
};
return (
<form
style={{
display: "flex",
flexDirection: "column",
border: "solid",
padding: 10,
}}
onSubmit={onSubmit}
>
<h3>Login</h3>
<input
value={username}
type="text"
onChange={(e) =>
e.target.value.length < 20
? setUsername(e.target.value)
: alert("Username cannot exceed 20 characters.")
}
style={{ marginBottom: 5 }}
/>
<input
value={password}
type="text"
onChange={(e) =>
e.target.value.length < 20
? setPassword(e.target.value)
: alert("Password cannot exceed 20 characters.")
}
style={{ marginBottom: 10 }}
/>
<button style={{ alignSelf: "center" }} onClick={onSubmit}>
Submit
</button>
</form>
);
};

export default App

8.

import React from "react";


import { useState } from "react";

const EMPTY_STAR =
"https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Five-
pointed_star.svg/1088px-Five-pointed_star.svg.png";
const FULL_STAR =
"https://upload.wikimedia.org/wikipedia/commons/thumb/2/29/Gold_Star.svg/
1200px-Gold_Star.svg.png";

function App() {
return <StarRating />;
}

const StarRating = () => {


const starIds = [1, 2, 3, 4, 5];
const [hovered, setHovered] = useState(0);
const [clicked, setClicked] = useState(0);
const getImg = (id) => {
return hovered >= id || clicked >= id ? FULL_STAR : EMPTY_STAR;
};

return (
<div
style={{
display: "flex",
justifyContent: "center",
padding: 20,
}}
>
{starIds.map((id) => (
<img
src={getImg(id)}
onMouseEnter={() => {
setHovered(id);
if (id < clicked) setClicked(0);
}}
onClick={() => setClicked(id)}
onMouseOut={() => setHovered(0)}
width={60}
height={60}
/>
))}
</div>
);
};

export default App;

9.

import React, { useEffect, useState } from "react";

function App() {
return (
<div style={{ display: "flex", justifyContent: "center", marginTop: 30 }}>
<GrowingButton />
</div>
);
}

const GrowingButton = () => {


const [size, setSize] = useState({ height: 40, width: 80 });
const [isGrowing, setIsGrowing] = useState(true);

const adjustSize = (height, width) => {


if (isGrowing && height < 200) {
setSize({ height: height + 10, width: width + 10 });
}
if (!isGrowing && height > 20) {
setSize({ height: height - 10, width: width - 10 });
}
};

useEffect(() => {
const timer = setInterval(() => adjustSize(size.height, size.width),
1000);
return () => {
clearInterval(timer);
};
}, [size, adjustSize]);

return (
<button
style={{ height: size.height, width: size.width }}
onClick={() => setIsGrowing(!isGrowing)}
>
{isGrowing ? "Shrink" : "Grow"}
</button>
);
};

export default App;

10.

import React, { useState } from "react";

const ONE =
"https://images.pexels.com/photos/2249528/pexels-photo-2249528.jpeg?
auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2";
const TWO =
"https://images.pexels.com/photos/1061141/pexels-photo-1061141.jpeg?
auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2";
const THREE =
"https://images.pexels.com/photos/2249530/pexels-photo-2249530.jpeg?
auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2";
const FOUR =
"https://images.pexels.com/photos/1061139/pexels-photo-1061139.jpeg?
auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2";
const FIVE =
"https://images.pexels.com/photos/1010973/pexels-photo-1010973.jpeg?
auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2";
const SIX =
"https://images.pexels.com/photos/4772874/pexels-photo-4772874.jpeg?
auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2";

function App() {
return <Captcha />;
}

const Captcha = () => {


const [open, setOpen] = useState(false);
const [answer, setAnswer] = useState(1);

return (
<div style={{ display: "flex", justifyContent: "center" }}>
<button
style={{ zIndex: 1, marginTop: 200 }}
onClick={() => {
setOpen(true);
setAnswer(Math.floor(Math.random() * 5 + 1));
}}
>
I'm not a robot
</button>
{open && (
<div
style={{
display: "flex",
justifyContent: "center",
flexDirection: "column",
marginTop: 100,
position: "fixed",
zIndex: 2,
}}
>
<Images answer={answer} setOpen={setOpen} />
</div>
)}
</div>
);
};

const Images = ({ answer, setOpen }) => {


const isAnswer = (id) => {
id == answer ? setOpen(false) : alert("Intruder!");
};

return (
<>
<div style={{ alignSelf: "center", fontSize: 20 }}>
{"Select " + answer}
</div>
<div style={{ display: "flex", justifyContent: "center", flex: "row" }}>
<img
src={ONE}
style={{ width: 200, height: 200 }}
onClick={() => isAnswer(1)}
/>
<img
src={TWO}
style={{ width: 200, height: 200 }}
onClick={() => isAnswer(2)}
/>
<img
src={THREE}
style={{ width: 200, height: 200 }}
onClick={() => isAnswer(3)}
/>
</div>
<div style={{ display: "flex", justifyContent: "center", flex: "row" }}>
<img
src={FOUR}
style={{ width: 200, height: 200 }}
onClick={() => isAnswer(4)}
/>
<img
src={FIVE}
style={{ width: 200, height: 200 }}
onClick={() => isAnswer(5)}
/>
<img
src={SIX}
style={{ width: 200, height: 200 }}
onClick={() => isAnswer(6)}
/>
</div>
</>
);
};

export default App;


11.

import React, { useState } from "react";

const INITIAL_LIST = [
{ name: "Tomatoes", value: 5.0 },
{ name: "Basil", value: 2.5 },
{ name: "Mozzarella", value: 9.99 },
];

function App() {
return <ItemValueList />;
}

const ItemValueList = () => {


const [list, setList] = useState(INITIAL_LIST);
const [newName, setNewName] = useState("");
const [newValue, setNewValue] = useState();

const onSubmit = (e) => {


e.preventDefault();
setList([...list, { name: newName, value: Number(newValue) }]);
setNewName("");
setNewValue();
};

return (
<div
style={{
display: "flex",
flexDirection: "column",
}}
>
<div
style={{
display: "flex",
flexDirection: "row",
justifyContent: "center",
margin: 60,
}}
>
<form onSubmit={onSubmit}>
<input
type={"text"}
value={newName}
required
onChange={(e) => setNewName(e.target.value)}
style={{ width: 92 }}
/>
<input
type={"number"}
required
value={newValue}
min={0}
step={0.01}
onChange={(e) => setNewValue(e.target.value)}
style={{ width: 92 }}
/>
<input type={"submit"} style={{ width: 100 }} />
</form>
</div>
{list.map((item) => {
console.log("working");
return (
<div
style={{
display: "flex",
flexDirection: "row",
justifyContent: "center",
}}
>
<div style={{ width: 100 }}>{item.name}</div>
<div style={{ width: 100 }}>{"$" + item.value}</div>
<div
style={{ textAlign: "center", width: 100 }}
onClick={() => setList(list.filter((ele) => ele !== item))}
>


</div>
</div>
);
})}
</div>
);
};

export default App;

12.

import React, { useState } from "react";


function App() {
return <Followers />;
}

const Followers = () => {


const [userList, setUserList] = useState([]);
const [newUser, setNewUser] = useState("");
const [user1, setUser1] = useState("");
const [user2, setUser2] = useState("");

const createUser = (e) => {


e.preventDefault();
if (!userList.some((user) => user.name == newUser)) {
setUserList([
...userList,
{ name: newUser, followers: [], following: [] },
]);
setNewUser("");
} else alert("This user already exists");
};

const submitNewFollow = (e) => {


e.preventDefault();
const user1Index = userList.findIndex((user) => user.name == user1);
const user2Index = userList.findIndex((user) => user.name == user2);

if (user1 == user2) alert(user1 + "cannot follow themselves.");


else if (user1Index == -1) alert(user1 + " is not yet a user");
else if (user2Index == -1) alert(user2 + " is not yet a user");
else if (userList[user1Index].following.includes(user2))
alert(user1 + " already follows " + user2);
else {
// create new objects to modify and insert into array copy
const newUser1Obj = { ...userList[user1Index] };
const newUser2Obj = { ...userList[user2Index] };
newUser1Obj.following = [...newUser1Obj.following, user2];
newUser2Obj.followers = [...newUser2Obj.followers, user1];
const shallowListCopy = [...userList];
shallowListCopy[user1Index] = newUser1Obj;
shallowListCopy[user2Index] = newUser2Obj;
setUserList(shallowListCopy);
setUser1("");
setUser2("");
}
};

return (
<div
style={{
display: "flex",
flexDirection: "column",
textAlign: "center",
}}
>
<form onSubmit={createUser}>
<input
style={{ width: 200, margin: 30 }}
value={newUser}
required
placeholder={"Enter new user"}
onChange={(e) => setNewUser(e.target.value)}
/>
</form>
<h4>User List</h4>
{userList.map((user) => (
<div
onClick={() => {
alert(
user.name +
" has " +
user.followers.length +
" followers and is following " +
user.following.length +
" people."
);
}}
style={{ cursor: "pointer" }}
>
{user.name}
</div>
))}
<form
style={{ display: "flex", margin: 50, alignSelf: "center" }}
onSubmit={submitNewFollow}
>
<input
style={{ width: 100 }}
value={user1}
required
onChange={(e) => setUser1(e.target.value)}
/>
<div style={{ margin: "0px 10px 0px 10px" }}>will now follow</div>
<input
style={{ width: 100 }}
value={user2}
required
onChange={(e) => setUser2(e.target.value)}
/>
<input type={"submit"} />
</form>
</div>
);
};

export default App;

13.

import React, { useState } from "react";


function App() {
const PLAYERS = [
"Raj",
"Kishore",
"Kumar",
"Vinay",
"Riju",
"Kiran",
"Varun",
"Ajay",
];

return <FormTeams players={PLAYERS} />;


}

const FormTeams = ({ players }) => {


const [team1, setTeam1] = useState([]);
const [team2, setTeam2] = useState([]);
const [remainingPlayers, setRemainingPlayers] = useState(players);
const [selectedTeam, setSelectedTeam] = useState(1);
const onClick = (player) => {
if (selectedTeam === 1) {
setTeam1([...team1, player]);
} else setTeam2([...team2, player]);

setRemainingPlayers(remainingPlayers.filter((person) => person !==


player));
};

return (
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
margin: 60,
}}
>
<div style={{ display: "flex", flexDirection: "row", flexWrap:
"wrap" }}>
{remainingPlayers.map((player) => (
<p1
onClick={() => onClick(player)}
style={{ margin: 5, cursor: "pointer" }}
>
{player}
</p1>
))}
</div>
<div style={{ display: "flex", flexDirection: "row", margin: 30 }}>
<button onClick={() => setSelectedTeam(selectedTeam === 1 ? 2 : 1)}>
{"Now selecting for Team " + selectedTeam}
</button>
<button
onClick={() => {
const shuffledPlayers = [...players];
shuffledPlayers.sort(() => 0.5 - Math.random());
setRemainingPlayers([]);
setTeam1(shuffledPlayers.slice(0, Math.floor(players.length /
2)));
setTeam2(
shuffledPlayers.slice(
Math.floor(players.length / 2),
players.length
)
);
}}
style={{ marginRight: 20, marginLeft: 20 }}
>
Randomize Teams
</button>
<button
onClick={() => {
setTeam1([]);
setTeam2([]);
setRemainingPlayers(players);
setSelectedTeam(1);
}}
>
Reset
</button>
</div>
<div
style={{
display: "flex",
flexDirection: "row",
alignItems: "center",
}}
>
<div style={{ marginRight: 25 }}>
<h4>Team 1</h4>
<div style={{ display: "flex", flexDirection: "row" }}>
{team1.map((player) => (
<p1 style={{ margin: 5 }}>{player}</p1>
))}
</div>
</div>
<div style={{ marginLeft: 25 }}>
<h4>Team 2</h4>
<div style={{ display: "flex", flexDirection: "row" }}>
{team2.map((player) => (
<p1 style={{ margin: 5 }}>{player}</p1>
))}
</div>
</div>
</div>
</div>
);
};
export default App;

14.

import React, { useEffect, useState } from "react";


import axios from "axios";

const useBitcoin = () => {


//Your Code Here
const [value, setValue] = useState();

useEffect(() => {
const fetchValue = async () => {
try {
const res = await axios.get(
"https://api.coindesk.com/v1/bpi/currentprice.json"
);
setValue(res.data.bpi.USD.rate_float);
} catch {
console.error("Failed to update price");
}
};

fetchValue();

const interval = setInterval(() => fetchValue(), 60000);


return () => clearInterval(interval);
}, []);

return value;
};

function App() {
const value = useBitcoin();
return (
<div style={{ display: "flex", justifyContent: "center" }}>
{value ? (
<h1>{"Bitcoin Price: $" + value + " USD"}</h1>
) : (
<h4>Fetching price...</h4>
)}
</div>
);

//Your Code Here


}

export default App;

15.

import React, { useEffect, useState } from "react";

const BASE_IMG_URL = "https://picsum.photos/seed/sameimage/300";

function App() {
return <CustomBlur />;
}
const CustomBlur = () => {
const [image, setImage] = useState(BASE_IMG_URL);
const [blur, setBlur] = useState(0);

useEffect(() => {
setImage(blur != 0 ? BASE_IMG_URL + "?blur=" + blur : BASE_IMG_URL);
}, [blur]);

return (
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
}}
>
<img src={image} width={300} height={300} style={{ margin: 60 }} />
<p1>Slide to blur</p1>
<input
type="range"
step="1"
min="0"
max="10"
value={blur}
onChange={(e) => setBlur(e.target.value)}
/>
</div>
);
};

export default App;

16.

import logo from './logo.svg';


import './App.css';

import React, { useMemo,useEffect, useState } from "react";


import axios from "axios";

const CURRENCY_NAME_TO_CODE = {
"United Arab Emirates Dirham": "AED",
"Afghan Afghani": "AFN",
"Albanian Lek": "ALL",
"Armenian Dram": "AMD",
"Netherlands Antillean Guilder": "ANG",
"Angolan Kwanza": "AOA",
"Argentine Peso": "ARS",
"Australian Dollar": "AUD",
"Aruban Florin": "AWG",
"Azerbaijani Manat": "AZN",
"Bosnia-Herzegovina Convertible Mark": "BAM",
"Barbadian Dollar": "BBD",
"Bangladeshi Taka": "BDT",
"Bulgarian Lev": "BGN",
"Bahraini Dinar": "BHD",
"Burundian Franc": "BIF",
"Bermudan Dollar": "BMD",
"Brunei Dollar": "BND",
"Bolivian Boliviano": "BOB",
"Brazilian Real": "BRL",
"Bahamian Dollar": "BSD",
"Bitcoin": "BTC",
"Bhutanese Ngultrum": "BTN",
"Botswanan Pula": "BWP",
"Belarusian Ruble": "BYN",
"Belize Dollar": "BZD",
"Canadian Dollar": "CAD",
"Congolese Franc": "CDF",
"Swiss Franc": "CHF",
"Chilean Unit of Account (UF)": "CLF",
"Chilean Peso": "CLP",
"Chinese Yuan (Offshore)": "CNH",
"Chinese Yuan": "CNY",
"Colombian Peso": "COP",
"Costa Rican Colón": "CRC",
"Cuban Convertible Peso": "CUC",
"Cuban Peso": "CUP",
"Cape Verdean Escudo": "CVE",
"Czech Republic Koruna": "CZK",
"Djiboutian Franc": "DJF",
"Danish Krone": "DKK",
"Dominican Peso": "DOP",
"Algerian Dinar": "DZD",
"Egyptian Pound": "EGP",
"Eritrean Nakfa": "ERN",
"Ethiopian Birr": "ETB",
"Euro": "EUR",
"Fijian Dollar": "FJD",
"Falkland Islands Pound": "FKP",
"British Pound Sterling": "GBP",
"Georgian Lari": "GEL",
"Guernsey Pound": "GGP",
"Ghanaian Cedi": "GHS",
"Gibraltar Pound": "GIP",
"Gambian Dalasi": "GMD",
"Guinean Franc": "GNF",
"Guatemalan Quetzal": "GTQ",
"Guyanaese Dollar": "GYD",
"Hong Kong Dollar": "HKD",
"Honduran Lempira": "HNL",
"Croatian Kuna": "HRK",
"Haitian Gourde": "HTG",
"Hungarian Forint": "HUF",
"Indonesian Rupiah": "IDR",
"Israeli New Sheqel": "ILS",
"Manx pound": "IMP",
"Indian Rupee": "INR",
"Iraqi Dinar": "IQD",
"Iranian Rial": "IRR",
"Icelandic Króna": "ISK",
"Jersey Pound": "JEP",
"Jamaican Dollar": "JMD",
"Jordanian Dinar": "JOD",
"Japanese Yen": "JPY",
"Kenyan Shilling": "KES",
"Kyrgystani Som": "KGS",
"Cambodian Riel": "KHR",
"Comorian Franc": "KMF",
"North Korean Won": "KPW",
"South Korean Won": "KRW",
"Kuwaiti Dinar": "KWD",
"Cayman Islands Dollar": "KYD",
"Kazakhstani Tenge": "KZT",
"Laotian Kip": "LAK",
"Lebanese Pound": "LBP",
"Sri Lankan Rupee": "LKR",
"Liberian Dollar": "LRD",
"Lesotho Loti": "LSL",
"Libyan Dinar": "LYD",
"Moroccan Dirham": "MAD",
"Moldovan Leu": "MDL",
"Malagasy Ariary": "MGA",
"Macedonian Denar": "MKD",
"Myanma Kyat": "MMK",
"Mongolian Tugrik": "MNT",
"Macanese Pataca": "MOP",
"Mauritanian Ouguiya": "MRU",
"Mauritian Rupee": "MUR",
"Maldivian Rufiyaa": "MVR",
"Malawian Kwacha": "MWK",
"Mexican Peso": "MXN",
"Malaysian Ringgit": "MYR",
"Mozambican Metical": "MZN",
"Namibian Dollar": "NAD",
"Nigerian Naira": "NGN",
"Nicaraguan Córdoba": "NIO",
"Norwegian Krone": "NOK",
"Nepalese Rupee": "NPR",
"New Zealand Dollar": "NZD",
"Omani Rial": "OMR",
"Panamanian Balboa": "PAB",
"Peruvian Nuevo Sol": "PEN",
"Papua New Guinean Kina": "PGK",
"Philippine Peso": "PHP",
"Pakistani Rupee": "PKR",
"Polish Zloty": "PLN",
"Paraguayan Guarani": "PYG",
"Qatari Rial": "QAR",
"Romanian Leu": "RON",
"Serbian Dinar": "RSD",
"Russian Ruble": "RUB",
"Rwandan Franc": "RWF",
"Saudi Riyal": "SAR",
"Solomon Islands Dollar": "SBD",
"Seychellois Rupee": "SCR",
"Sudanese Pound": "SDG",
"Swedish Krona": "SEK",
"Singapore Dollar": "SGD",
"Saint Helena Pound": "SHP",
"Sierra Leonean Leone": "SLL",
"Somali Shilling": "SOS",
"Surinamese Dollar": "SRD",
"South Sudanese Pound": "SSP",
"São Tomé and Príncipe Dobra (pre-2018)": "STD",
"São Tomé and Príncipe Dobra": "STN",
"Salvadoran Colón": "SVC",
"Syrian Pound": "SYP",
"Swazi Lilangeni": "SZL",
"Thai Baht": "THB",
"Tajikistani Somoni": "TJS",
"Turkmenistani Manat": "TMT",
"Tunisian Dinar": "TND",
"Tongan Pa'anga": "TOP",
"Turkish Lira": "TRY",
"Trinidad and Tobago Dollar": "TTD",
"New Taiwan Dollar": "TWD",
"Tanzanian Shilling": "TZS",
"Ukrainian Hryvnia": "UAH",
"Ugandan Shilling": "UGX",
"United States Dollar": "USD",
"Uruguayan Peso": "UYU",
"Uzbekistan Som": "UZS",
"Venezuelan Bolívar Soberano": "VES",
"Vietnamese Dong": "VND",
"Vanuatu Vatu": "VUV",
"Samoan Tala": "WST",
"CFA Franc BEAC": "XAF",
"East Caribbean Dollar": "XCD",
"Special Drawing Rights": "XDR",
"CFA Franc BCEAO": "XOF",
"CFP Franc": "XPF",
"Yemeni Rial": "YER",
"South African Rand": "ZAR",
"Zambian Kwacha": "ZMW",
"Zimbabwean Dollar": "ZWL",
};

function CurrencyConverter() {
const [initial, setInitial] = useState(0);
const [fromCurrency, setFromCurrency] = useState("Indian Rupee");
const [toCurrency, setToCurrency] = useState("United States Dollar");
const [exchangeRate, setExchangeRate] = useState(null);

useEffect(() => {
const fetchExchangeRate = async () => {
try {
const response = await axios.get(
https://api.exchangerate-api.com/v4/latest/$
{CURRENCY_NAME_TO_CODE[fromCurrency]}
);
setExchangeRate(response.data.rates[CURRENCY_NAME_TO_CODE[toCurrency]]);
} catch (error) {
console.error("Error fetching exchange rates:", error);
}
};

fetchExchangeRate();
}, [fromCurrency, toCurrency]);

const converted = useMemo(() => {


if (exchangeRate === null) {
return "Loading..."; // Or any other placeholder while fetching exchange rate
}

return initial * exchangeRate;


}, [initial, exchangeRate]);

return (
<div>
<h2>Currency Converter</h2>
<form>
<input type="number" value={initial} onChange={(e) =>
setInitial(e.target.valueAsNumber || 0)} />
<select value={fromCurrency} onChange={(e) => setFromCurrency(e.target.value)}>
{Object.keys(CURRENCY_NAME_TO_CODE).map((currency) => (
<option key={currency} value={currency}>
{currency}
</option>
))}
</select>
<span>to</span>
<select value={toCurrency} onChange={(e) => setToCurrency(e.target.value)}>
{Object.keys(CURRENCY_NAME_TO_CODE).map((currency) => (
<option key={currency} value={currency}>
{currency}
</option>
))}
</select>
</form>
<p>
{initial} {fromCurrency} is equal to {converted} {toCurrency}
</p>
</div>
);
}

export default CurrencyConverter;


17.

import React, { useState } from "react";


import { BrowserRouter, Link, Routes, Route } from "react-router-dom";

function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="protectedPage" element={<ProtectedPage />} />
</Routes>
</BrowserRouter>
);
}
const Home = () => (
<Link to="/protectedPage" style={{ margin: 30 }}>
<button>Locked</button>
</Link>
);

const ProtectedPage = () => {


const [unlocked, setUnlocked] = useState(false);

return unlocked ? (
<div>Secret message</div>
) : (
<Captcha setUnlocked={setUnlocked} />
);
};

const Captcha = ({ setUnlocked }) => {


return (
<div style={{ display: "flex", justifyContent: "center" }}>
<div
style={{
display: "flex",
justifyContent: "center",
flexDirection: "column",
marginTop: 100,
position: "fixed",
zIndex: 2,
}}
>
<Images
answer={Math.floor(Math.random() * 5 + 1)}
setUnlocked={setUnlocked}
/>
</div>
</div>
);
};

const Images = ({ answer, setUnlocked }) => {


const ONE =
"https://images.pexels.com/photos/2249528/pexels-photo-2249528.jpeg?
auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2";
const TWO =
"https://images.pexels.com/photos/1061141/pexels-photo-1061141.jpeg?
auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2";
const THREE =
"https://images.pexels.com/photos/2249530/pexels-photo-2249530.jpeg?
auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2";
const FOUR =
"https://images.pexels.com/photos/1061139/pexels-photo-1061139.jpeg?
auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2";
const FIVE =
"https://images.pexels.com/photos/1010973/pexels-photo-1010973.jpeg?
auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2";
const SIX =
"https://images.pexels.com/photos/4772874/pexels-photo-4772874.jpeg?
auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2";

const isAnswer = (id) => {


id == answer ? setUnlocked(true) : alert("Intruder!");
};

return (
<>
<div style={{ alignSelf: "center", fontSize: 20 }}>
{"Select " + answer}
</div>
<div style={{ display: "flex", justifyContent: "center", flex: "row" }}>
<img
src={ONE}
style={{ width: 200, height: 200 }}
onClick={() => isAnswer(1)}
/>
<img
src={TWO}
style={{ width: 200, height: 200 }}
onClick={() => isAnswer(2)}
/>
<img
src={THREE}
style={{ width: 200, height: 200 }}
onClick={() => isAnswer(3)}
/>
</div>
<div style={{ display: "flex", justifyContent: "center", flex: "row" }}>
<img
src={FOUR}
style={{ width: 200, height: 200 }}
onClick={() => isAnswer(4)}
/>
<img
src={FIVE}
style={{ width: 200, height: 200 }}
onClick={() => isAnswer(5)}
/>
<img
src={SIX}
style={{ width: 200, height: 200 }}
onClick={() => isAnswer(6)}
/>
</div>
</>
);
};

export default App;

18.

import { useEffect, useState } from "react";

function App() {
return <Timers />;
}

const Timers = () => {


const [seconds, setSeconds] = useState(30);
const [timerList, setTimerList] = useState([]);

useEffect(() => {
const interval = setInterval(
() =>
setTimerList((list) =>
list
.map((timer) => {
return {
...timer,
left: timer.total - (new Date().getTime() - timer.start),
};
})
.filter((timer) => timer.left > 500)
),
100
);
return () => clearInterval(interval);
}, []);

return (
<>
<div style={{ display: "flex", justifyContent: "center" }}>
<form onSubmit={(e) => e.preventDefault()}>
<input
type={"number"}
value={seconds}
onChange={(e) => setSeconds(e.target.value)}
min={1}
required
/>
<input
type={"submit"}
onClick={() =>
seconds > 0 &&
setTimerList([
...timerList,
{
start: new Date().getTime(),
total: seconds * 1000,
left: seconds * 1000,
},
])
}
value={"Add Timer"}
/>
</form>
</div>
<div
style={{ display: "flex", justifyContent: "center", flexWrap:
"wrap" }}
>
{timerList.map((item) => (
<div key={item.start} style={{ margin: 30 }}>
{(item.left / 1000).toFixed(1)}
</div>
))}
</div>
</>
);
};

export default App;

19.

import { useState } from "react";

const TASKS = [
{
task: "Clean bedroom",
subtasks: ["Do laundry", "Organize desk", "Wipe floors"],
},
{
task: "Study",
subtasks: ["Review chemistry", "Do a React coding challenge"],
},
{
task: "Build website",
subtasks: ["Choose tech stack", "Design pages", "Develop", "Publish"],
},
];

function App() {
const [tasks, setTasks] = useState(TASKS);

return (
<div
style={{
display: "flex",
justifyContent: "center",
marginTop: 30,
}}
>
<TasksAndSubtasks taskArray={tasks} setTaskArray={setTasks} />
</div>
);
}

const TasksAndSubtasks = ({ taskArray, setTaskArray }) => {


const [completed, setCompleted] = useState(() =>
taskArray.map((taskObj) => taskObj.subtasks.map(() => false))
);

const flipCompleted = (outerIndex, innerIndex) =>


setCompleted(
completed.map((arr, index) =>
index !== outerIndex
? arr
: arr.map((bool, jIndex) => (jIndex !== innerIndex ? bool : !bool))
)
);

const clearCompleted = () => {


const completedCopy = [];

setTaskArray(
taskArray.filter((_, index) => {
if (completed[index].some((value) => !value)) {
completedCopy.push(completed[index]);
return true;
} else return false;
})
);
setCompleted(completedCopy);
};

return (
<div>
<input
type={"button"}
onClick={clearCompleted}
value={"Clear completed tasks"}
/>
{taskArray.map((obj, i) => (
<>
<p>
{completed[i].some((value) => !value) ? (
obj.task
) : (
<s>{obj.task}</s>
)}
</p>
<div style={{ marginLeft: 20 }}>
{obj.subtasks.map((subtask, j) => (
<p onClick={() => flipCompleted(i, j)}>
{completed[i][j] ? <s>{subtask}</s> : subtask}
</p>
))}
</div>
</>
))}
</div>
);
};

export default App;

20.

import React, { useState } from 'react';


const items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
{ id: 4, name: 'Item 4' },
];

const SearchFilter = () => {


const [search, setSearch] = useState('');

const filteredItems = items.filter((item) =>


item.name.toLowerCase().includes(search.toLowerCase())
);

const handleChange = (e) => {


setSearch(e.target.value);
};

return (
<div>
<input
type="text"
placeholder="Search items..."
value={search}
onChange={handleChange}
/>
<ul>
{filteredItems.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
};
function App() {
return (
<div className="App">
<SearchFilter />
</div>
);
}

export default App;

21.

import React, { useState } from 'react';

const Counter = () => {


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

const increment = async () => {


await new Promise((resolve) => setTimeout(resolve, 1000));
setCount(count + 1);
};

const decrement = () => {


setCount(count - 1);
};

return (
<div>
<h2>Count: {count}</h2>
<button onClick={increment}>Increment Async</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};

function App() {
return (
<div className="App">
<Counter />
</div>
);
}

export default App;

22.

App.js

// App.js

import React from "react";


import { Link, Route, BrowserRouter as Router, Routes } from "react-router-
dom";
import About from "./About";
import Blog from "./Blog";
import Home from "./Home";

function App() {
return (
<Router>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/blog">Blog</Link>
</li>
</ul>
</nav>

<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/blog" element={<Blog />} />
</Routes>
</Router>
);
}

export default App;

home.js

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

const Home = () => {


return <div>Home Page</div>;
};

export default Home;

blog.js

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

const Blog = () => {


return <div>Blog Page</div>;
};

export default Blog;

about.js

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

const About = () => {


return <div>About Page</div>;
};
export default About;

You might also like