Skip to content

Reference

Core functionality for the reactpy-router package.

create_router(compiler)

A decorator that turns a route compiler into a router

Source code in reactpy_router/core.py
35
36
37
38
39
40
41
def create_router(compiler: RouteCompiler[R]) -> Router[R]:
    """A decorator that turns a route compiler into a router"""

    def wrapper(*routes: R) -> ComponentType:
        return router_component(*routes, compiler=compiler)

    return wrapper

A component that renders a link to the given path

Source code in reactpy_router/core.py
74
75
76
77
78
79
80
81
82
83
@component
def link(*children: VdomChild, to: str, **attributes: Any) -> VdomDict:
    """A component that renders a link to the given path"""
    set_location = _use_route_state().set_location
    attrs = {
        **attributes,
        "to": to,
        "onClick": lambda event: set_location(Location(**event)),
    }
    return _link(attrs, *children)

route(path, element, *routes)

Create a route with the given path, element, and child routes

Source code in reactpy_router/core.py
30
31
32
def route(path: str, element: Any | None, *routes: Route) -> Route:
    """Create a route with the given path, element, and child routes"""
    return Route(path, element, routes)

router_component(*routes, compiler)

A component that renders the first matching route using the given compiler

Source code in reactpy_router/core.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
@component
def router_component(
    *routes: R,
    compiler: RouteCompiler[R],
) -> VdomDict | None:
    """A component that renders the first matching route using the given compiler"""

    old_conn = use_connection()
    location, set_location = use_state(old_conn.location)

    resolvers = use_memo(
        lambda: tuple(map(compiler, _iter_routes(routes))),
        dependencies=(compiler, hash(routes)),
    )

    match = use_memo(lambda: _match_route(resolvers, location))

    if match is not None:
        element, params = match
        return html._(
            ConnectionContext(
                _route_state_context(element, value=_RouteState(set_location, params)),
                value=Connection(old_conn.scope, location, old_conn.carrier),
            ),
            _history({"on_change": lambda event: set_location(Location(**event))}),
        )

    return None

use_params()

Get parameters from the currently matching route pattern

Source code in reactpy_router/core.py
86
87
88
def use_params() -> dict[str, Any]:
    """Get parameters from the currently matching route pattern"""
    return _use_route_state().params

use_query(keep_blank_values=False, strict_parsing=False, errors='replace', max_num_fields=None, separator='&')

See :func:urllib.parse.parse_qs for parameter info.

Source code in reactpy_router/core.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def use_query(
    keep_blank_values: bool = False,
    strict_parsing: bool = False,
    errors: str = "replace",
    max_num_fields: int | None = None,
    separator: str = "&",
) -> dict[str, list[str]]:
    """See :func:`urllib.parse.parse_qs` for parameter info."""
    return parse_qs(
        use_location().search[1:],
        keep_blank_values=keep_blank_values,
        strict_parsing=strict_parsing,
        errors=errors,
        max_num_fields=max_num_fields,
        separator=separator,
    )

A simple router implementation for ReactPy

CONVERSION_TYPES: dict[str, ConversionInfo] = {'str': {'regex': '[^/]+', 'func': str}, 'int': {'regex': '\\d+', 'func': int}, 'float': {'regex': '\\d+(\\.\\d+)?', 'func': float}, 'uuid': {'regex': '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', 'func': uuid.UUID}, 'path': {'regex': '.+', 'func': str}} module-attribute

The supported conversion types

router = create_router(SimpleResolver) module-attribute

The simple router

ConversionInfo

Bases: TypedDict

Information about a conversion type

Source code in reactpy_router/simple.py
63
64
65
66
67
68
69
class ConversionInfo(TypedDict):
    """Information about a conversion type"""

    regex: str
    """The regex to match the conversion type"""
    func: ConversionFunc
    """The function to convert the matched string to the expected type"""

func: ConversionFunc instance-attribute

The function to convert the matched string to the expected type

regex: str instance-attribute

The regex to match the conversion type

SimpleResolver

A simple route resolver that uses regex to match paths

Source code in reactpy_router/simple.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class SimpleResolver:
    """A simple route resolver that uses regex to match paths"""

    def __init__(self, route: Route) -> None:
        self.element = route.element
        self.pattern, self.converters = parse_path(route.path)
        self.key = self.pattern.pattern

    def resolve(self, path: str) -> tuple[Any, dict[str, Any]] | None:
        match = self.pattern.match(path)
        if match:
            return (
                self.element,
                {k: self.converters[k](v) for k, v in match.groupdict().items()},
            )
        return None

Types for reactpy_router

Route dataclass

A route that can be matched against a path

Source code in reactpy_router/types.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@dataclass(frozen=True)
class Route:
    """A route that can be matched against a path"""

    path: str
    """The path to match against"""

    element: Any = field(hash=False)
    """The element to render if the path matches"""

    routes: Sequence[Self]
    """Child routes"""

    def __hash__(self) -> int:
        el = self.element
        key = el["key"] if is_vdom(el) and "key" in el else getattr(el, "key", id(el))
        return hash((self.path, key, self.routes))

element: Any = field(hash=False) class-attribute instance-attribute

The element to render if the path matches

path: str instance-attribute

The path to match against

routes: Sequence[Self] instance-attribute

Child routes

RouteCompiler

Bases: Protocol[R]

Compile a route into a resolver that can be matched against a path

Source code in reactpy_router/types.py
42
43
44
45
46
class RouteCompiler(Protocol[R]):
    """Compile a route into a resolver that can be matched against a path"""

    def __call__(self, route: R) -> RouteResolver:
        ...

RouteResolver

Bases: Protocol

A compiled route that can be matched against a path

Source code in reactpy_router/types.py
49
50
51
52
53
54
55
56
57
class RouteResolver(Protocol):
    """A compiled route that can be matched against a path"""

    @property
    def key(self) -> Key:
        """Uniquely identified this resolver"""

    def resolve(self, path: str) -> tuple[Any, dict[str, Any]] | None:
        """Return the path's associated element and path params or None"""

key: Key property

Uniquely identified this resolver

resolve(path)

Return the path's associated element and path params or None

Source code in reactpy_router/types.py
56
57
def resolve(self, path: str) -> tuple[Any, dict[str, Any]] | None:
    """Return the path's associated element and path params or None"""

Router

Bases: Protocol[R]

Return a component that renders the first matching route

Source code in reactpy_router/types.py
35
36
37
38
39
class Router(Protocol[R]):
    """Return a component that renders the first matching route"""

    def __call__(self, *routes: R) -> ComponentType:
        ...