Home > Enterprise >  React Native 0.6 - Replace Header when Navigating to Child
React Native 0.6 - Replace Header when Navigating to Child

Time:09-28

I'm trying to replace the header bar when navigating to a child screen in the stack, or sibling let's say.

Basically my main stack looks like this :

<MainStack.Navigator initialRouteName="Home">
      <MainStack.Screen name="Home" options={{
        headerTitle: () => <LogoTitle />,
        tabBarLabel: '',
        tabBarIcon: ({ color }) => (
          <AntDesign name='home' backgroundColor='black' color={color} size={23} />
        )
      }} component={HomeStackScreens} />
    </MainStack.Navigator>

And the LogoTitle here :

function LogoTitle() {

  const navigation = useNavigation(); 

  return (
    <View style={{ width: width, flexDirection: 'row', justifyContent: 'space-between' }}>
      <View>
        <Text style={{ fontWeight: 'bold' }}>Brand</Text>
      </View>
      <View></View>
      <View style={{ width: 50 }}>
        <AntDesign name='dingding' backgroundColor="#ff" size={23} onPress={() => navigation.reset({
          index: 0,
          routes: [{ name: 'New' }],
        })} />
      </View>
    </View>
  );
}

And finally the HomeStackScreen :

function HomeStackScreens() {


  const { username } = React.useContext(UserContext) ;

  return (
    <HomeStack.Navigator initialRouteName="Home">
      <HomeStack.Screen name="Home" options={{ headerShown: false }} component={HomeScreen} />
      <HomeStack.Screen name="New" options={{ title: username }} component={NewScreen} />
     
    </HomeStack.Navigator>
  );
}

When I click on the AntDesign icon, I want to navigate to the "new" screen, and replace the LogoTitle header with one that would be like "< Username" (where < allows to go back).

Basically, it looks like I want to push a screen on the stack, but without showing the parent / previous screen's header.

How can I achieve this ?

(I'm new to React Native sorry if it's a silly question).

My initial thought is that I should be updating a state, like the navigation state reflected by useNavigation, but I'm unsure how exactly (and I guess creating a custom context for that would be redundant as it feels like useNavigation could provide this behavior).

CodePudding user response:

On the NewScreen you can use the below:

useEffect(()=>{
      navigation.setOptions({ headerTitle: 'Title of the Screen'  })
  },[])

You can use whatever title you want. you can pass the title from previous screen as props too.

CodePudding user response:

Actually I should just remove the title from the MainStack Screen header, and place it inside the HomeStack Screen header.

It works as expected.

  • Related