Passing Params to Links in Expo

If you use the Expo framework along with expo-router for navigation, passing parameters to different pages is common.

Expo Router has its own Link component, making passing parameters easy.

Creating Links with Parameters

To navigate with parameters, use the Link component. Define the href prop as an object containing the pathname (destination) and params (an object with key-value pairs representing the parameters to pass).

<Link
  href={{
    pathname: "/details",
    params: { id: 123, info: "additional info here" },
  }}
>
  Go to Details
</Link>

Here's an example product page with Links:

import { View, Text } from "react-native";
import { Link } from "expo-router";

export default function Home() {
  // Products array to simulate a list of products
  const products = [
    { id: 1, name: "Product 1" },
    { id: 2, name: "Product 2" },
    // Add more products as needed
  ];

  return (
    <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
      <Text>Product Listing</Text>
      {products.map((product) => (
        <Link
          key={product.id}
          href={{
            pathname: "/product-details",
            params: { productId: product.id },
          }}
        >
          View {product.name}
        </Link>
      ))}
    </View>
  );
}

Accessing Parameters

On the screen that receives the parameters, use the useLocalSearchParams hook to access them. This hook returns an object containing the parameters defined in the link.

const { id, info } = useLocalSearchParams();

Or so we can complete our shop example:

import { useLocalSearchParams, Link } from "expo-router";
import { useEffect } from "react";
import { View, Text } from "react-native";

// ProductDetails component
function ProductDetails() {
  // Using the useLocalSearchParams hook to access parameters passed through the link
  const { productId } = useLocalSearchParams();

  useEffect(() => {
    if (productId) {
      // Optionally, fetch detailed information about the product using the productId
    }
  }, [productId]);

  return (
    <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
      <Text>Product Details Screen</Text>
      <Text>Product ID: {productId}</Text>
    </View>
  );
}

By using the Link component and the useLocalSearchParams hook, Expo makes the job easy!

ExpoReact Native
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.