Reputation: 117
I have an array of objects:
const arrayOfObjects = [
{ name: 'Sushi', price: 10 },
{ name: 'Pizza',price: 5 }
];
I'm mapping trough them to generate child Components.
const List = arrayOfObjects.map(item => (
<Child name={item.name} price={item.price} propFunc={parentFunc}></Child>
));
In a function in the parent component I need values from the array as well as an input value from the child component.
const parentFunc = (arg1, arg2) => {
setItems(prev => {
return [...prev, { meal: arg1, amount: arg2 }];
});
};
In the Child component I'm not using the props, just sending them back:
const Child = props => {
const childFunc = event => {
const var1 = event.target.value;
const var2 = props.name;
const var3 = props.price;
props.propFunc(var1, var2, var3);
};
};
This seems redundant. Can I access the values from the array without sending them back and forth?
I'm looking for a solution that doesn't use other React Hooks and doesn't alter the array.
Upvotes: 0
Views: 59
Reputation: 85102
You can do this by creating a function for each child, with those functions knowing the corresponding item:
const list = arrayOfObjects.map(item => (
<Child propFunc={(event) => parentFunc(event, item.name, item.price))} />
));
// ...
const Child = props => {
const childFunc = event => {
props.propFunc(event.target.value);
};
};
Upvotes: 1