Code 1:
"use client";
import { useState } from "react";
const Home = () => {
const [myList, setMyList] = useState([]);
const [name, setName] = useState("");
const fillList = () => {
setMyList(["Makyus", "Razzie", "LaNay"]);
};
const addToList = () => {
setMyList([...myList, name]);
}
return (
<>
<h1>Working with Lists and useEffect() Hook</h1>
<button onClick={fillList}>Fill List</button><br/>
<input
type="text"
placeholder="Enter a name"
value={name}
onChange={(e) => {
setName(e.target.value);
}}
/>
<button onClick={addToList}>Add To List</button>
{/* <ul>
{
myList.map((student) => {
return(
<li>{student}</li>
);
})
}
</ul> */}
<table>
<tbody>
{myList.map((student) => {
return (
<tr>
<td>{student}</td>
</tr>
);
})}
</tbody>
</table>
</>
);
};
export default Home;
Code 2:
"use client";
import { useEffect, useState } from "react";
const Home = () => {
const [myList, setMyList] = useState([]);
const [stud_name, setName] = useState("");
const [stud_balance, setBalance] = useState(0);
const [totalBalance, setTotalBalance] = useState(0 );
const fillList = () => {
setMyList([
{ name: "Makyus", balance: 10000 },
{ name: "Razzie", balance: 5000 },
{ name: "LaNay", balance: 3000 },
]);
};
const addToList = () => {
setMyList([...myList, {name:stud_name, balance:stud_balance}]);
};
const getTotalBalance = () => {
// var total = 0;
// myList.forEach(student => {
// total += parseFloat(student.balance);
// })
// return total;
return myList.reduce((acc, student)=> acc + parseFloat(student.balance), 0);
}
//initial render
useEffect(() => {
fillList();
}, []);
//when myList changes size
useEffect(() => {
setTotalBalance(getTotalBalance());
}, [myList])
return (
<>
<h1>Working with Lists and useEffect() Hook</h1>
<input
type="text"
placeholder="Enter a name"
value={stud_name}
onChange={(e) => {
setName(e.target.value);
}}
/>
<input
type="number"
placeholder="Enter balance"
value={stud_balance}
onChange={(e) => {
setBalance(e.target.value);
}}
/>
<button onClick={addToList}>Add To List</button>
{/* <ul>
{
myList.map((student) => {
return(
<li>{student}</li>
);
})
}
</ul> */}
<table>
<tbody>
{myList.map((student, index) => {
return (
<tr key={index}>
<td style={{ border: "1px solid #000" }}>{student.name}</td>
<td style={{ border: "1px solid #000" }}>{student.balance}</td>
</tr>
);
})}
</tbody>
</table>
<h3>Total Balance - {totalBalance}</h3>
</>
);
};
export default Home;
No comments:
Post a Comment