I have the 1 dimension array called [cars] and values are added through an input box using React JS.
//initial array setup
const cars = [ ];
const [itemsList, setItemsList] = useState([ {brand: ""} ]);
//function called every time I add a new value
const carsUpdate = (e, index) => {
const list = [...itemsList];
list[index]["brand"] = e.target.value;
setItemsList(list);
};
After adding 3 cars I get the following.
const cars = [ { brand: “Fiat” }, { brand: “Ford” }, { brand: “Renault” } ];
The above works perfectly for 1 a dimension array type.
Now, I’m trying to make it multi-dimension by adding an extra property [colors] to the array which contains another array The idea is to get this type of result by adding colors separately and individually through other input boxes.
const cars = [
{ brand: “Fiat”, colors: [ “red”, “green” ] },
{ brand: “Ford”, colors: [ “blue”, “yellow” ] },
{ brand: “Renault”, colors: [ “red”, “white” ] },
]
I have modified the following:
const [itemsList, setItemsList] = useState([ {brand: "", colors: [ ] } ])
but I’m struggling to modify the function carsUpdate to update the colors property with new values.
const carsUpdate = (e, index) => { let list = [...itemsList]; let innerList = []; innerList = list[index]["colors"]; innerList.push(e.target.value); list[index][colors] = innerList; setItemsList(list); };