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
- delete index.js
- delete App.js - ACTUALLY, LET'S RENAME IT TO Login.jsx BECAUSE WE MAY USE IT LATER.
- Add a folder named app to the project folder (the router looks here for the route files)
- Add a file named index.jsx to the app folder (this is like the home page/screen for the app)
- Put some starter code in index.jsx:
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
- This wil allow you to force the app to reload, which you have to do occasionally
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
- Add about.jsx to the app folder
- Use the rnfes snippet to put the starter code in it.
- You can capitalize the A (in two places if you want)
- Add contact.jsx to the app folder (and use rnfes)
- You can capitliaze the C if you want
The Expo router will automatically create routes for:
- /about
- /contact
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.