Search code examples
react-nativereact-navigationreact-native-web

Hide route params from the url with react-navigation


I am adapting a ReactNative mobile app to ReactNative Web. The app is done with react-navigation.

Currently, every time I set the params of a route (either through navigate or setParams), those params show in the URL. I end up with bad looking URLs like so: http://localhost:19006/me/undefined?user=%5Bobject%20Object%5D

Either that or the URL contains irrelevant data for the user and generally looks messy.

Is there a way to not show the route params inside the URL?


Solution

  • You should re-consider if params is an appropriate place to have this data if you don't want in the URL. That you think that the URL contains irrelevant data is a sign that the data doesn't belong in the navigation state.

    If you visit a screen directly from a URL, it should render the same as when you navigated to it porgrammatically. If you're passing something in params, it means that that information is needed for the screen to render correctly, and if you remove it from the URL, then that information is lost. Consider that it's possible to open the page directly from a URL, either on Web or with a deep link. If the required data isn't available, then it's not going to work.

    In your case, seems like you're passing a full user object (maybe not, hard to say without code). Ideally, this object should be in your global store instead of params, and you should only pass the user id in params. Then you should gran the full object from your global store using that id, or trigger a data fetch if the objet isn't fetched yet (if needed).

    You didn't specify the version of React Navigation in your question. In v5, you can customize how your params are stringified to URLs, and how they are parsed back using the stringify and parse options:

    const linking = {
      screens: {
        Profile: {
          path: 'user/:id',
          parse: {
            id: (id) => id.replace(/^@/, '')
          },
          stringify: {
            id: (id) => `@{id}`,
          },
        },
      },
    };
    

    This should help you with making URLs look prettier, and handle cases where params are not simple strings. However you can't omit params from the URL altogether since they are necessary data for the screen to render.

    More details: https://reactnavigation.org/docs/configuring-links#passing-params