How do I hide the previous Stack header when I navigate to the new Stack screen in expo router?

84 Views Asked by At

I'm using expo router, and want to know how I can remove the previous stack header from the screen, the replace method is not working as expected.

My file structure looks like this:

-app
 -exercise
   -layout.tsx
   -index.tsx
   -Active.tsx
 -layout.tsx

app/layout.tsx

app/exercise/layout.tsx

<Stack>
  <Stack.Screen
    name="index"
    options={{
      headerShown: false,
      presentation: "modal",
    }}
  />
  <Stack.Screen
    name="Active"
    options={{
      headerShown: true,
    }}
  />
</Stack>

currently:

When I'm home, and I press on an exercise, I navigate to the index.tsx of the exercise folder

router.navigate(`/exercise`); 

When I'm on that index, and I press start, I'm sent to the /exercise/Active.tsx

router.replace({
          pathname: "exercise/Active",
        });

when I'm on the exercise/Active, I get two stack screens on top, the exercise and the active enter image description here

What I want: when I'm on the active screen, I don't want the exercise header to be shown, I know how to remove the Active header by simply adding "headerShow:false" in the exercise/layout Stack, but how do I remove the exercise header, which exists on the app/layout.

I can't set the headerShown to false on the app/layout on exercise layout, because that'll remove the header when I'm on the app/index screen, I only want to remove it when I'm on the active screen, and when I go back from the /exercise/active screen to /exercise/index screen I want the /exercise header to be shown.

2

There are 2 best solutions below

0
Muath_01 On

I figured this out, and I thought I would answer it because I feel like it's a common problem for someone just starting out on app/dev.

The trick here is to set headerShown for the exercise route on the app/layout to false and on the app/exercise/layout set the headerShown for the index to true and add a headerTitle "exercise".

This will give the desired outcome.

0
John McCants On

In your app/layout you probably have a stack. If so do this. This hides the extra header from all the screens on your exercise stack (app/exercise/layout)

<Stack> 

  <Stack.Screen name="exercise" options={{headerShown: false}} /> 

  <Stack.Screen name="index" /> 

</Stack>

If you don't have a Stack in your app/layout then use a instead and it will solve the issue.

So something like this

const Layout = () => {
   return <Slot />
}