typescriptreact-routerreact-router-dom

Navigate with query params in remix-run/react router


I'm useing the new data Apis createBrowserRouter. I'm using it like this:

router.tsx

import { createBrowserRouter } from 'react-router-dom';
import { allRoutes } from './allRouts.tsx';
import type { Router } from '@remix-run/router/dist/router';

export const router: Router = createBrowserRouter(allRoutes);

Then in another router action file I use the router navigate function:

routerAction.tsx

export const routerAction = async ( 
    value: string | number
): Promise<void> => { 
            return router.navigate(value.toString());
    }
};

From what I could read in the type documentation (could not find information on the router instance on the site):

A Router instance manages all navigation and data loading/mutations

A Router instance manages all navigation and data loading/mutations

The question is how could I use this router to navigate with search parameters like I would with useSearchParams?


Solution

  • The router.navigate function has the following signature

    /**
     * Navigate to the given path
     * @param to Path to navigate to
     * @param opts Navigation options (method, submission, etc.)
     */
    navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;
    

    It takes a to prop that is of type To

    /**
     * Describes a location that is the destination of some navigation, either via
     * `history.push` or `history.replace`. This may be either a URL or the pieces
     * of a URL path.
     */
    export type To = string | Partial<Path>;
    

    Which is either a path string or a partial Path object

    /**
     * The pathname, search, and hash values of a URL.
     */
    export interface Path {
      /**
       * A URL pathname, beginning with a /.
       */
      pathname: string;
    
      /**
       * A URL search string, beginning with a ?.
       */
      search: string;
    
      /**
       * A URL fragment identifier, beginning with a #.
       */
      hash: string;
    }
    

    You can use the Path object parameter to specify the target pathname and search parameters.

    Example:

    export const routerAction = async ( 
      value: string | number
    ): Promise<void> => { 
      return router.navigate({
        pathname: value.toString(),
        search: /* stringified search params, i.e. "?foo=bar" */,
      });
    };