Search code examples
react-nativeexpourl-routingexpo-router

Unable to get React Native Expo app to navigate to a particular route


I got stuck yesterday when trying to get Expo's file-based routing working for a particular route on a project I'm working on. The folder structure looks as follows:

index.tsx
_layout.tsx
+not-found.tsx
(home)
    (tabs)
    _layout.tsx
        (learning)
            lessons
                (quiz)
                    _layout.tsx
                    [lessonId].tsx <---- Where I'm trying to navigate to
                _layout.tsx
                [unitId].tsx <---- Where I'm navigating from
            _layout.tsx
            index.tsx
        profile
        _layout.tsx
      

I'm trying to navigate from the route that is the [unitId].tsx file to /(quiz)/[lessonId]. For some reason it doesn't work, instead always taking me to +not-found.tsx, implying that my efforts at routing aren't correct.

This is what the _layout.tsx file in the (learning) directory looks like:

import { Stack } from 'expo-router'

const UnitScreenLayout = () => {
    return (
        <Stack>
            <Stack.Screen
                name="index"
            />
            <Stack.Screen 
                name="lessons"
            />
        </Stack>
    )
}

export default UnitScreenLayout

And this is what the _layout.tsx in the lessons directory looks like (exports and imports excluded):

const LessonsScreenLayout = () => {
    return (
        <Stack screenOptions={{ headerShown: false }}>
            <Stack.Screen 
                name="(quiz)"
            />
            <Stack.Screen 
                name="[unitId]"
            />
        </Stack>
    )
}

In (learning)/index, it works when I try navigate to lessons/[unitId] using the following:

router.navigate({ pathname: `/lessons/${unit.id}` })

However, when I try navigate to /(quiz)/${lesson.id} from lessons/[unitId] it doesn't work. I don't understand why, given that the layout files are set up in basically the same way. The _layout.tsx file in (quiz) only contains a Stack.Screen for [lessonId].

I've tried various things including creating an index.tsx file inside (quiz) and trying to navigate to that, removing the brackets from (quiz) everywhere they exist and adding (quiz)/[lessonId] to the _layout.tsx file in the lessons directory, but nothing has worked.


Solution

  • The brackets arounds the folder names are whats known as a Group. They purely organise the files but do not create a new route at all.

    In your case [lessonId].tsx and [unitId].tsx exists in the same level, even though it isn't shown through the folder structure. You should remove the brackets around quiz and try again, or rethink how you are organising the routes.