Reputation: 16168
I have a parent component that creates a child component that passes an "onPress" to the parent,
Works fine, but now need to pass some value from child to parent...
the parent component:
const filterBarTapped = ( index:any )=> {
console.log('tongo:', index )
}
const Charter = ({ isSingle, isDarkMode, data1, data2 }: Charterprops) => {
return (
<View>
{ Object.keys(data1).length > 6 && <TabBar data={data1} onPress={() => filterBarTapped()}/>} ...
the child:
const handleClick = (index:any) => {
setSelectedTab(index)
console.log("sale index:", index)
onPress()
}
return (
<View style={{
flexDirection: "row",
justifyContent: 'space-around',
alignItems: 'center',
}}>
{tabs.map(p => (
<Tab
title={p.title}
onPress={() => handleClick(p.itemIndex)}
itemIndex={p.itemIndex}
selectedItem={selectedTab} />
))}
</View>
)
}
But I'm getting,
tongo: undefined
So, how to pass the index to the parent for my onPress?
cheers
Upvotes: 0
Views: 2230
Reputation: 6152
Instead of
<TabBar data={data1} onPress={() => filterBarTapped()}/>}
You can directly pass the filterBarTapped
function
<TabBar data={data1} onPress={filterBarTapped}/>}
In this way, whatever value is passed from onPresss
event will be available to filterBarTapped
function. and the code becomes little bit more maintainable.
Upvotes: 1
Reputation: 1191
You need to pass the value to the onPress callback
child
onPress(index)
then update it in the filter function
onPress={(index) => filterBarTapped(index)}
In order to be accessible on filterBarTapped
function
Shortcut:
Since onPress
and filterBarTapped
have the same number of args you can just write:
onPress={filterBarTapped}
on the parent component
Upvotes: 2