React Navigation v6: How to set state variable of parent component from custom tab bar component?

101 Views Asked by At

I'm using React-Navigation v6 in my React Native app. I make a custom tab bar in my MaterialTopTabNavigator, and in it I have a TextInput in which I want to set a state variable in the parent component. Here's the render method of my parent component:

render() {

  const setParentState = (text) => this.setState({text})
  const Tab = createMaterialTopTabNavigator();
  
  const TabBar = ({state, descriptors, navigation, position}) => {
    return (
      <TextInput
        onChangeText={text => setParentState(text)}
      />
    )
  }

  return (
    <Tab.Navigator
      tabBar={props => <TabBar {...props}/>}
    >
      ...
    </Tab.Navigator>
  )
}

So here I create a function setParentState() that calls setState() in the parent component. I try to call it from the TabBar component, but it doesn't successfully set the state in the parent component.

Why does it not set the state in the parent component? And how can I get it to do so?

"react-native": "0.69.10"
"@react-navigation/material-top-tabs": "^6.6.2"
0

There are 0 best solutions below