Question

How do I pass props in a Link using Expo Router?

Answer and Explanation

Passing props in a Link using Expo Router involves serializing the data into the URL and then accessing it on the destination page. Here’s a breakdown of how to achieve this:

1. Using Query Parameters:

The most common way to pass props is by encoding them as query parameters in the URL. Expo Router automatically handles this for you when you use the Link component or the router.push() method.

2. Creating the Link with Query Parameters:

When navigating with the Link component, you can add query parameters directly to the href prop.

Example:

<Link href={{ pathname: '/details', params: { id: '123', name: 'Example' } }}>
  Go to Details
</Link>

Alternatively, you can use router.push() programmatically:

import { useRouter } from 'expo-router';

const MyComponent = () => {
  const router = useRouter();

  const handlePress = () => {
    router.push({ pathname: '/details', params: { id: '123', name: 'Example' } });
  };

  return (
    <Button title="Go to Details" onPress={handlePress} />
  );
};

3. Accessing the Parameters in the Destination Page:

On the destination page, you can access these parameters using the useSearchParams hook provided by Expo Router.

Example:

import { useSearchParams } from 'expo-router';

const DetailsPage = () => {
  const { id, name } = useSearchParams();

  return (
    <View>
      <Text>ID: {id}</Text>
      <Text>Name: {name}</Text>
    </View>
  );
};

export default DetailsPage;

4. Important Considerations:

- Serialization: All parameters passed through the URL must be serializable to strings. Complex objects should be converted to strings (e.g., using JSON.stringify) before being passed, and parsed back on the receiving end.

- URL Length Limit: Be mindful of the maximum URL length. Large amounts of data can exceed this limit, potentially causing issues.

- Type Safety: useSearchParams returns strings. You may need to parse these strings into the correct data types (e.g., using parseInt for numbers).

5. Example with JSON Serialization:

Passing an object:

// Sending Page
const router = useRouter();
const data = { item: { id: 1, description: 'Some Description' } };
router.push({ pathname: '/details', params: { data: JSON.stringify(data) } });

// Receiving Page
import { useSearchParams } from 'expo-router';
const DetailsPage = () => {
  const { data } = useSearchParams();
  const parsedData = JSON.parse(data);

  return (<Text>{parsedData.item.description}</Text>);
};

In summary, Expo Router makes it straightforward to pass props between pages by serializing them into the URL. Use Link or router.push() to navigate with parameters, and useSearchParams to extract those parameters on the destination page. Remember to handle serialization, URL length limits, and type safety appropriately.

More questions