react-nativeexpoexpo-router

How can I pass parameters using expo-router?


This is in my index.js file and I'm trying to pass the access token to the home screen so I can use it to fetch notifications.

import { router } from "expo-router";

result = JSON.parse(result);

router.replace("Homescreen", { token: result.access_token });

and my Homescreen.js file

import { Button, View, Text } from "react-native";

export default function Homescreen({ route }) {
  const { token } = route.params;
  console.log(token, );
    
  return (
    <View>
      <Text>Homepage</Text>
    </View>
  );
}

I am getting undefined for token, anyone knows how to fix this?


Solution

  • use params

    //index.js
    import { router } from "expo-router";
    result = JSON.parse(result);
    
    router.push({
       pathname: "Homescreen",
       params: {
         token: result.access_token
       }
    })
    

    .

    //Homescreen.js
    import { Button, View, Text } from "react-native";
    import { useLocalSearchParams } from "expo-router";
    
    export default function Homescreen() {
      const { token } = useLocalSearchParams();
      console.log(token, );
    
      return (
        <View>
          <Text>Homepage</Text>
        </View>
      );
    }
    

    Please refer to this page:

    https://docs.expo.dev/router/reference/search-parameters/