KarimK3
KarimK3

Reputation: 23

How to pass param as an object with React-Navigation deep linking?

I use React-Navigation deep linking to get params from an Url but I would like to pass these params to an object. Now I do this :

prefixes: [Linking.makeUrl('/'), 'https://test.app', 'https://*.test.app'],
  config: {
    screens: {
      App: {
        screens: {
          Chat: {
            path: 'chat/:firstName/:lastName/:birthdate',
            parse: {
              firstName: (firstName: string) => decodeURIComponent(firstName),
              lastName: (lastName: string) => decodeURIComponent(lastName),
              birthdate: (birthdate: string) => decodeURIComponent(birthdate),
            },
          },

This is the result :

 const { firstName, lastName, birthdate} = route.params

And what I need is an object with inside firstName, lastName, birthdate :

const { userObject } = route.params

Upvotes: 2

Views: 5403

Answers (1)

Tom S
Tom S

Reputation: 431

You can use getStateFromPath to configure the params however you like.

Something like this should work. Note: I haven't tested with nested screens. You may need to modify this slightly to handle the nested screens.

import { getStateFromPath } from '@react-navigation/native';

const linking = {
  prefixes: [Linking.makeUrl('/'), 'https://test.app', 'https://*.test.app'],
  config: {
    screens: {
      App: {
        screens: {
          Chat: {
            path: 'chat/:firstName/:lastName/:birthdate',
            parse: {
              firstName: (firstName: string) => decodeURIComponent(firstName),
              lastName: (lastName: string) => decodeURIComponent(lastName),
              birthdate: (birthdate: string) => decodeURIComponent(birthdate),
            },
          },
        },
      },
    },
  },
  getStateFromPath: (path, options) => {
    const state = getStateFromPath(path, options);
    const newState = {
      ...state,
      routes: state.routes.map(route => {
        if (route.name === 'Chat') {
          // modify your params however you like here!
          return {
            ...route,
            params: { userObject: route.params }
          }
        } else {
          return route
        }
      }),
    };
    return newState;
  },
}

Upvotes: 8

Related Questions