1.
Show/Hide Text
import "./styles.css";
import { useState } from "react";
export default function App() {
const [show, setShow] = useState(false);
const clickhandler = () => {
setShow(!show);
};
return (
<div className="App">
<button onClick={clickhandler}>Show/Hide</button>
{show ? <p>Welcome to react</p> : null}
</div>
);
}
2. Timer
import "./styles.css";
import { useState } from "react";
export default function App() {
const [timer, setTimer] = useState(0);
const startTimer = () => {
// Complete this function
window.myTimer = setInterval(() => {
//myTimer is attached to the window object so that it can be accessed globally and used
with clearinterval
setTimer((timer) => timer + 1);
}, 1000);
};
const stopTimer = () => {
// Complete this function
clearInterval(window.myTimer);
};
const resetTimer = () => {
// Complete this function
clearInterval(window.myTimer);
setTimer(0);
};
return (
<div className="container">
<h1>Timer</h1>
<span> {Math.trunc(timer / 60)} mins </span>
<span> {timer % 60} secs</span>
<div>
<button onClick={startTimer}>Start</button>
<button onClick={stopTimer}>Stop</button>
<button onClick={resetTimer}>Reset</button>
</div>
</div>
);
}
3. To centre an using Transform:
Position: absolute;
Top:50%;
Left:50%;
Transform: Translate(0,-50%)
4. Psedo Classes:
5. button:nth-of-type(1) {
6. background: green;
7. }
8. button:nth-of-type(2) {
9. background: red;
10. }
11. button:nth-of-type(3) {
12. background: yellow;
13. }
5. ToDo List
import "./styles.css";
import { useState } from "react";
/*
INSTRUCTIONS:
Create a "todo"(add cities) app with the following criteria.
1. The user can add new cities
2. The user can remove existing cities items
*/
export default function App() {
const [input, setInput] = useState("");
const [cities, setCities] = useState([]);
const chnageHandler = (e) => {
setInput(e.target.value);
};
const addCities = () => {
setCities([...cities, input]);
setInput("");
};
const deleteHandler = (index) => {
const updatedCitites = cities.filter((_, i) => i !== index);
setCities(updatedCitites);
};
const handleKeyDown = (e) => {
if (e.key === "Enter") {
addCities();
};
return (
<div className="App">
<input
type="text"
name="data"
value={input}
placeholder="Enter Cities"
onChange={chnageHandler}
onKeyDown={handleKeyDown}
/>
<button onClick={addCities}>Add</button>
<ul style={{ textAlign: "center" }}>
{cities.map((item, index) => (
<div>
<li
style={{
margin: "5px",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
}}
>
{item}
<button
onClick={() => deleteHandler(index)}
style={{ marginLeft: "10px" }}
>
Delete
</button>
</li>
</div>
))}
</ul>
</div>
);