Labreact
Labreact
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.
)
}
3.
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>
);
}
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}>
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 />
}
5.
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} />
}
6.
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>
)}
</>
);
};
7.
function App() {
return (
<div
style={{
display: "flex",
justifyContent: "center",
paddingTop: 20,
}}
>
<ValidatedForm />
</div>
);
}
8.
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 />;
}
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>
);
};
9.
function App() {
return (
<div style={{ display: "flex", justifyContent: "center", marginTop: 30 }}>
<GrowingButton />
</div>
);
}
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>
);
};
10.
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 />;
}
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>
);
};
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>
</>
);
};
const INITIAL_LIST = [
{ name: "Tomatoes", value: 5.0 },
{ name: "Basil", value: 2.5 },
{ name: "Mozzarella", value: 9.99 },
];
function App() {
return <ItemValueList />;
}
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>
);
};
12.
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>
);
};
13.
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.
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();
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>
);
15.
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>
);
};
16.
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]);
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>
);
}
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>
);
return unlocked ? (
<div>Secret message</div>
) : (
<Captcha setUnlocked={setUnlocked} />
);
};
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>
</>
);
};
18.
function App() {
return <Timers />;
}
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>
</>
);
};
19.
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>
);
}
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>
);
};
20.
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>
);
}
21.
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>
);
}
22.
App.js
// App.js
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>
);
}
home.js
// Home.js
import React from "react";
blog.js
// Blog.js
import React from "react";
about.js
// About.js
import React from "react";