React Native - Layout Files
This lesson is part of a series on React Native.
Step 7 - Layout files
- Create a new file called _layout.jsx in the app folder.
When the app folder has a _layout.jsx file in it, the app will automatically render it (instead of the index.jsx file).
Our first version of the _layout file will use a Slot to put the content from the other pages into it:
import { StyleSheet, Text, View } from 'react-native'
import { Slot } from 'expo-router'
const RootLayout = () => {
return (
<View style={{flex:1}}>
<Text>Header</Text>
<Slot />
<Text>Footer</Text>
</View>
)
}
export default RootLayout
const styles = StyleSheet.create({})
We did something very similar to this in our React apps in web 3, we created a layout component
Run the app and notice how all the pages/screens are wrapped inside the layout.
Stack Navigation
By simply changing the Slot component in the layout file to Stack (and importing Stack instead of Slot from expo-router). You'll automatically get a Back button at the top of each page:
import { StyleSheet, Text, View } from 'react-native'
import React from 'react'
import { Stack } from 'expo-router' <<<<<<<<<<<<<<<
const RootLayout = () => {
return (
<View style={{flex:1}}>
<Text>Header</Text>
<Stack /> <<<<<<<<<<<<<<<<<
<Text>Footer</Text>
</View>
)
}
export default RootLayout
const styles = StyleSheet.create({})
- As you navigate to pages, each page gets added to the stack.
- when you press the back button, the current page is removed from the stack
A better way to use Stacks
Change the code in the layout file to look like this:
import { StyleSheet, Text, View } from 'react-native'
import React from 'react'
import { Stack } from 'expo-router'
const RootLayout = () => {
return (
<Stack>
<Stack.Screen name="index" options={{title:"Home"}} />
<Stack.Screen name="about" options={{title:"About"}} />
<Stack.Screen name="contact" options={{title:"Contact", headerShown: false}} />
</Stack>
)
}
export default RootLayout
const styles = StyleSheet.create({})
- Note that each stack screen has options that you can set
- The title property allows you to control what shows in the header (the default is the file name)
- The contact page does not include the header because we set headerShown to false
You can apply options to to all screens in the stack. Update the opening Stack element in the layout to look like this:
<Stack screenOptions={{
headerStyle: {backgroundColor:'orange'},
headerTintColor: 'yellow'
}}>