A dynamic route allows matching one or multiple paths based on a dynamic segment embedded in the URL. This segment is in the form of a variable, such as a unique identifier, and your app doesn't know the exact segment ahead of time.
A dynamic segment of a route is created by wrapping a file's name in square brackets. For example, [id].tsx
.
Link
to navigate to a dynamic routeNavigating from one route to a dynamic route is done by providing query parameters to the Link
component either statically or using the href
object.
For example, the following code allows you to navigate to the dynamic route statically using query parameters:
import { Link } from "expo-router";
<Link href="/details/1">View first user details</Link>;
You can also use the href
object to provide a pathname
which takes the value of the dynamic route and passes params
:
import { Link } from "expo-router";
<Link
href={{
pathname: "/details/[id]",
params: { id: "bacon" },
}}>
View user details
</Link>;
Dynamic segments of a URL are accessible with a route parameter in the route component. For example, you can use the useLocalSearchParams
hook which returns the URL parameters for the selected route.
import { useLocalSearchParams } from "expo-router";
import { View, Text } from "react-native";
export default function DetailsScreen() {
const { id } = useLocalSearchParams();
return (
<View>
<Text>Details of user {id} </Text>
</View>
);
}