Routers, Routes, and Links
We include built-in components that automatically handle routing, which enable Single Page Application (SPA) behavior.
Routers and Routes¶
The browser_router
component is one possible implementation of a Router. Routers takes a series of route objects as positional arguments and render whatever element matches the current location.
Note
The current location is determined based on the browser's current URL and can be found by checking the use_location
hook.
Here's a basic example showing how to use browser_router
with two routes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Here we'll note some special syntax in the route path for the second route. The "any"
type is a wildcard that will match any path. This is useful for creating a default page or error page such as "404 NOT FOUND".
Browser Router¶
The syntax for declaring routes with the browser_router
is very similar to the syntax used by starlette
(a popular Python web framework). As such route parameters are declared using the following syntax:
/my/route/{param}
/my/route/{param:type}
In this case, param
is the name of the route parameter and the optionally declared type
specifies what kind of parameter it is. The available parameter types and what patterns they match are are:
Type | Pattern |
---|---|
str (default) | [^/]+ |
int | \d+ |
float | \d+(\.\d+)? |
uuid | [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} |
slug | [-a-zA-Z0-9_]+ |
path | .+ |
any | .* |
So in practice these each might look like:
/my/route/{param}
/my/route/{param:int}
/my/route/{param:float}
/my/route/{param:uuid}
/my/route/{param:path}
Any route parameters collected from the current location then be accessed using the use_params
hook.
Pitfall
While it is possible to use route parameters to capture values from query strings (such as /my/route/?foo={bar}
), this is not recommended. Instead, you should use the use_search_params
hook to access query string values.
Route Links¶
Links between routes should be created using the link component. This will allow ReactPy to handle the transition between routes and avoid a page reload.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|