Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 374
KarimK3 Avatar asked Dec 18 '25 16:12

KarimK3


1 Answers

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;
  },
}

like image 183
Tom S Avatar answered Dec 21 '25 10:12

Tom S