import React, { useEffect, useState } from "react";
export default function App() {
const items = [
{ store: { name: "store a", id: 0 }, months: ["june", "july"] },
{ store: { name: "store b", id: 2 }, months: ["agust", "septm"] },
{ store: { name: "store c", id: 3 }, months: ["novem", "decemb"] },
];
return (
<table>
{items.map((item, index) => {
const storeName = item.store.name;
return (
<tr key={item.store.id}>
<th>{storeName}</th>
{item.months.map((month, i) => (
<td>
<input type="text" />
</td>
))}
<td style={{ width: "100px" }}>total:</td>
</tr>
);
})}
</table>
);
}
I want to implement this ui and show summation of inputs in each row how should I implement its functionality?
CodePudding user response:
import React, { useEffect, useState } from "react";
export default function App() {
const [inputData, setInputData] = useState(null);
const items = [
{ store: { name: "store a", id: 0 }, months: ["june", "july"] },
{ store: { name: "store b", id: 2 }, months: ["agust", "septm"] },
{ store: { name: "store c", id: 3 }, months: ["novem", "decemb"] },
];
useEffect(() => {
let data = {};
items.forEach((item) => {
data = { ...data, [item.store.name]: [] };
});
setInputData(data);
}, []);
function getSum(total, num) {
return total Number(num);
}
return (
<table>
{inputData &&
items.map((item, index) => {
const storeName = item.store.name;
return (
<tr key={item.store.id}>
<th>{storeName}</th>
{item.months.map((month, i) => (
<td>
<input
type="text"
value={inputData && inputData[items[index].store.name][i]}
onChange={(e) => {
let montData = [...inputData[storeName]];
montData[i] = e.target.value;
setInputData({
...inputData,
[storeName]: montData,
});
}}
/>
</td>
))}
<td style={{ width: "100px" }}>
total: {inputData[storeName].reduce(getSum, 0)}
</td>
</tr>
);
})}
</table>
);
}