React Native - File Based Routing

This lesson is part of a series on React Native.

Step 6 - File Based Routing

For navigation from one screen to another, we can use file-based routing.

There's another popular framework called NextJS, which is based on React and uses file-based routing.

This means that the navigation and routing is determined by the file and folder structure of your project.

First we need to install the routing package

npx expo install expo-router react-native-safe-area-context react-native-screens expo-linking expo-constants expo-status-bar

Then update the main property in the package.json file:

"main": "expo-router/entry",

You need to put all your 'screen' code in a folder named app, so go ahead and create that folder (in the project folder)

We need to make some changes to the project file

import { StyleSheet, Text, View } from 'react-native'

const Home = () => {
  return (
    <View>
      <Text>Home</Text>
    </View>
  )
}

export default Home

const styles = StyleSheet.create({})

If your app is running, you'll have to stop and start it again:

# To run in the browser:
npm run web

# To run with Expo Go:
npx expo start

Remember that you can shake the device to see the developer control panel

We'll be using the browser for this activity becaue it has the URL bar so that we can see how the navigation and routing is working.

You should see your index page/screen.

Add an About screen

The Expo router will automatically create routes for:

Then add Link elements to index.jsx:

import { StyleSheet, Text, View } from 'react-native'
import { Link } from 'expo-router'  ///////////////////////// IMPORT THIS

const Home = () => {
  return (
    <View>
      <Text>Home</Text>
      ///////////////////////////////////////// ADD THESE LINK ELEMENTS
      <Link href="/about">About</Link>
      <Link href="/contact">Contact</Link>
    </View>
  )
}

export default Home

const styles = StyleSheet.create({})

Then apply the exact same styles to about and contact that are in index.jsx (copy the styles object to about and contact, then apply the container and text styles)

Add links in the contact and about screens

On the contact and about pages, add links back to the home page (and apply styles)

Run the app in the browser and keep an eye on the URL bar.

Obviously you cant see a URL bar when running on a mobile device.