To display the full array content when a new item is added.
DisplayItems.js:
export default function DisplayItems(props)
{
return (
<div>
{
props.items.map
((i) =>
{
return (
<div>
ID: {i.id}, Name: {i.name}
</div>
)
}
)
}
</div>
)
}
App.js:, lines with //??? not working and no error, but OK if replaced by // OK if : ..., difference is to move array into an attribute of an object: inventory.items.
import DisplayItems from './DisplayItems';
export default function App()
{
const [items, setItems] = useState([]); // ??? array
// OK if: const [inventory, setInventory] = useState({ items: []});
const receiveAndAddAnItem = (newItem) =>
{
let vitems = items; // ???
// OK if: let vitems = inventory.items;
let vid = vitems.length;
let i = {id: vid, name: newItem.name};
vitems.push(i);
setItems(vitems); // ??? not trigger DisplayItems for re-render
// OK if: setInventory({items: vitems});
}
return (
<div className="App">
<AddItem callback={receiveAndAddAnItem} />
<hr />
<DisplayItems items={items}/> // ???
// OK if: items=(inventory.items)
</div>
);
}
Update Thanks to @NicholasTower, OK if copy then change: let vitems = [...items]