Skip to content

Creating a Custom Router

Custom routers can be used to define custom routing logic for your application. This is useful when you need to implement a custom routing algorithm or when you need to integrate with an existing URL routing system.


Step 1: Creating a custom resolver

You may want to create a custom resolver to allow ReactPy to utilize an existing routing syntax.

To start off, you will need to create a subclass of ReactPyResolver. Within this subclass, you have two attributes which you can modify to support your custom routing syntax:

  • param_pattern: A regular expression pattern that matches the parameters in your URL. This pattern must contain the regex named groups name and type.
  • converters: A dictionary that maps a type to it's respective regex pattern and a converter func.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from typing import ClassVar

from reactpy_router.resolvers import ConversionInfo, ReactPyResolver


# Create a custom resolver that uses the following pattern: "{name:type}"
class CustomResolver(ReactPyResolver):
    # Match parameters that use the "<name:type>" format
    param_pattern: str = r"<(?P<name>\w+)(?P<type>:\w+)?>"

    # Enable matching for the following types: int, str, any
    converters: ClassVar[dict[str, ConversionInfo]] = {
        "int": ConversionInfo(regex=r"\d+", func=int),
        "str": ConversionInfo(regex=r"[^/]+", func=str),
        "any": ConversionInfo(regex=r".*", func=str),
    }

Step 2: Creating a custom router

Then, you can use this resolver to create your custom router...

1
2
3
4
5
6
from example.resolvers import CustomResolver

from reactpy_router.routers import create_router

# This can be used in any location where `browser_router` was previously used
custom_router = create_router(CustomResolver)

Last update: January 12, 2025