Walter Monecke Walter Monecke - 3 years ago 93
React JSX Question

Pass callback with parameters to parent component

I am asking something that is probably trivial but that has been bugging me for a while.

Lets say we have a CHILD component that renders some buttons:

const Picker = ({ data, label, visible, cancelCallback, onPressCallback }) => {

function renderRow (data) {
return data.map((el) => {
return (
<TouchableOpacity
style={listViewItemContainer}
key={el.label}
onPress={}
>
<Text style={listViewItem}> { el.label } </Text>
</TouchableOpacity>
);
});
}

return (
<Modal
visible={visible}
animationType="fade"
onRequestClose={() => {}}
transparent={true}
>


<View style={listViewContainerStyle}>
{ renderRow(data) }
</View>


</Modal>
);
};


Now when I press one of those buttons I want to make a callback to the parent BUT I want to pass some parameters like the label of the element pressed. Something like:

<TouchableOpacity
style={listViewItemContainer}
key={el.label}
onPress={onPressCallback(el.label)} // onPressCallback is a Prop passed to the child
>
<Text style={listViewItem}> { el.label } </Text>
</TouchableOpacity>


And then handle the logic in the parent component.
How can I do this?

Answer Source

Like this.

   onPress={() => onPressCallback(el.label)} 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download