I’m new in React and I need your help figuring out how to solve the problem that I’ve been trying to solve. I’m trying to make a dynamic table in which I can create new input field of a layer just by clicking a plus button. There are going to be 3 sub layers for a main layer and there might be multiple layers. The part where I’m stuck is I don’t know how to add the data in array(using map()) and track them according to their their parent layer. Also, what I want to focus on is that the array will be empty at first and filled from the UI part. I’ve also uploaded a rough diagram of what I want to make. Please feel free to ask more if you don’t understand my question. I’ve also attached the code that I’ve done so far. Don’t hesitate to tell if the code is wrong at all.
import React, { useState, useEffect } from "react";
const Table = () => {
const dataFields = [];
const addField = (parentName, layerName, divReference, data) => {
switch (parentName) {
case "Food":
if (layerName == "FIRST_LAYER") {
dataFields[dataFields.length] = {
title: data.title,
batch: data.batch,
price: data.price,
};
} else if (layerName === "SECOND_LAYER") {
dataFields.forEach((fields) => {
if (fields.title === data.immediateParentName) {
fields.child = {
title: data.title,
batch: data.batch,
price: data.price,
};
}
});
} else if (layerName === "THIRD_LAYER") {
dataFields.forEach((fields) => {
if (fields.child.title === data.immediateParentName) {
fields.child.child = {
title: data.title,
batch: data.batch,
price: data.price,
};
}
});
}
break;
}
console.log(dataFields);
};
useEffect(() => {
addField("Food", "FIRST_LAYER", null, {
title: "Fruit",
batch: "batch",
price: "price",
});
addField("Food", "SECOND_LAYER", null, {
title: "Apple",
batch: "batch",
price: "price",
immediateParentName: "Fruit",
});
addField("Food", "THIRD_LAYER", null, {
title: "AppleSauce",
batch: "batch",
price: "price",
immediateParentName: "Apple",
});
}, []);
const [dataField, setDataField] = useState([dataFields]);
function addFields() {
setDataField((asset) => {
return [
...asset,
{
title: "FIRST_LAYER",
price: "",
batch: "",
},
];
});
}
return (
<div className="m-4">
<h3 className="text-center">lists</h3>
<table>
<thead>
<tr>
<th>S.N.</th>
<th>title</th>
<th>batch number</th>
<th>price</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
Foods{" "}
<button
className="btn btn-success btn-sm"
onClick={() =>
addFields("Food", "FIRST_LAYER", null, {
title: "apple",
batch: "01",
price: "100",
})
}
>
+
</button>
</td>
</tr>
{dataFields.map((data, index) => {
return (
<tr key={index}>
<td>{index + 1}</td>
<td value={data.parentName}>Food</td>
<td>
<button className="btn btn-success btn-sm">+</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
};
export default Table;