Skip to content

kapv89/better-react-native-expo-router

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

better-react-native-expo-router

Just copy the file router.tsx in your project and start using.


Usage

In app/[...container].tsx:

import router from './router';
import { usePathname } from 'expo-router';

router()
  .addRoute('/shop', ShopScreen)
  .addRoute('/shop/{item}', ItemScreen)
  .addRoute('/item-designer', ItemDesignerScreen)
;

// In app/[...container].tsx
export default function Container() {
    const pathname = usePathname();

    return (
        <>
            ...
            {router.execute(pathname, extraProps)}
            ...
        </>
    )
}

In ItemDesignerScreen component's file:

import router from './router';
import { usePathname } from 'expo-router';

router('/item-designer')
    .addRoute('/theme-picker/{color}')
    .addRoute('/pixel-art/{color}')

export default function ItemDesignerScreen() {
    const pathname = usePathname();

    return (
        <>
            ...
            {router('/item-designer').execute(pathname, extraProps)}
            ...
        </>
    )
}

or

import router from './router';
import { usePathname } from 'expo-router';

const r = router('/item-designer')
    .addRoute('/theme-picker/{color}')
    .addRoute('/pixel-art/{color}')

export default function ItemDesignerScreen() {
    const pathname = usePathname();

    return (
        <>
            ...
            {r.execute(pathname, extraProps)}
            ...
        </>
    )
}

Routed components receive the following prop by via the router, and any extra props you pass:

export type RoutableComponent = (props: {routeExecution: RouteExecution}) => JSX.Element

export type Route = {
  pattern: string,
  regexp: RegExp,
  pathParameters: string[],
}

export type RouteExecution = {
  route: Route,
  args: Record<string, string>,
}

Most of expo-router navigation methods supported in all routers:

class Router {
  ...
  navigate(href: Parameters<(typeof expoRouter)['navigate']>[0]) {
    return expoRouter.navigate(href);
  }

  push(href: Parameters<(typeof expoRouter)['push']>[0]) {
    return expoRouter.push(href);
  }

  replace(href: Parameters<(typeof expoRouter)['replace']>[0]) {
    return expoRouter.replace(href);
  }

  back() {
    return expoRouter.back();
  }

  canGoBack() {
    return expoRouter.canGoBack();
  }
}

About

it's better, try it

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published