Search code examples
react-nativeexpoexpo-router

Expo, Why can't I use router in _layout?


I try to implement a settings button in my header from the _layout, using an icon I made an button to redirect to "/settings", however it only works in browsers, when I try it in android, nothing happens.

import { Redirect, Stack, useRouter } from "expo-router";
import { TouchableOpacity } from "react-native";
import { Ionicons } from "@expo/vector-icons";

export default function RootLayout() {
  const router = useRouter();

  // Define the redirect function inside the component
  const redirect = () => {
    console.log("Navigating to settings");
    router.navigate("/settings");
  };
  
  return  (
    <Stack 
      screenOptions={{
        headerStyle: {
          backgroundColor: 'lightblue',
        },
        headerTitleStyle: {
          fontWeight: 'bold',
          color: 'white',
        },
        title: 'Weerklank',
        headerRight: () => (
          <TouchableOpacity
            onPress={redirect}
            style={{ marginRight: 15 }}
          >
            <Ionicons name="settings" size={24} color="white" />
          </TouchableOpacity>
        )
      }}>
      <Stack.Screen name="settings" 
        options={{
          title: 'Settings', // Override the title for the settings screen
      }}
    />
    </Stack>
  );
}

Solution

  • Found the solution, TouchableOpacity doens't behave well on android when using OnPress, so the solution is to use OnPressIn

    headerRight: () => (
      <TouchableOpacity
        onPressIn={redirect}
        style={{ marginRight: 15 }}
      >
        <Ionicons name="settings" size={24} color="white" />
      </TouchableOpacity>
    )
    

    This did the trick and now it works.