React Native - Layout Files

This lesson is part of a series on React Native.

Step 7 - Layout files

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({})

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({})

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'
}}>