Skip to content

Commit d31f149

Browse files
committed
handle client-side history changes
1 parent a6f7d23 commit d31f149

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

js/src/index.js

+16-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React from "react";
1+
import React, { useEffect } from "react";
22
import ReactDOM from "react-dom";
33
import htm from "htm";
44

@@ -15,6 +15,21 @@ export function bind(node, config) {
1515
};
1616
}
1717

18+
export function History({ onChange }) {
19+
// capture changes to the browser's history
20+
useEffect(() => {
21+
const listener = () => {
22+
onChange({
23+
pathname: window.location.pathname,
24+
search: window.location.search,
25+
});
26+
};
27+
window.addEventListener("popstate", listener);
28+
return () => window.removeEventListener("popstate", listener);
29+
});
30+
return null;
31+
}
32+
1833
export function Link({ to, onClick, children, ...props }) {
1934
const handleClick = (event) => {
2035
event.preventDefault();

reactpy_router/core.py

+10-5
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
from reactpy.core.types import VdomChild, VdomDict
1919
from reactpy.types import ComponentType, Context, Location
2020
from reactpy.web.module import export, module_from_file
21+
from reactpy import html
2122

2223
from reactpy_router.types import Route, RouteCompiler, Router, RouteResolver
2324

@@ -44,6 +45,7 @@ def router_component(
4445
) -> ComponentType | None:
4546
old_conn = use_connection()
4647
location, set_location = use_state(old_conn.location)
48+
print(location)
4749

4850
resolvers = use_memo(
4951
lambda: tuple(map(compiler, _iter_routes(routes))),
@@ -54,9 +56,12 @@ def router_component(
5456

5557
if match is not None:
5658
element, params = match
57-
return ConnectionContext(
58-
_route_state_context(element, value=_RouteState(set_location, params)),
59-
value=Connection(old_conn.scope, location, old_conn.carrier),
59+
return html._(
60+
ConnectionContext(
61+
_route_state_context(element, value=_RouteState(set_location, params)),
62+
value=Connection(old_conn.scope, location, old_conn.carrier),
63+
),
64+
_history({"on_change": lambda event: set_location(Location(**event))}),
6065
)
6166

6267
return None
@@ -113,9 +118,9 @@ def _match_route(
113118
return None
114119

115120

116-
_link = export(
121+
_link, _history = export(
117122
module_from_file("reactpy-router", file=Path(__file__).parent / "bundle.js"),
118-
"Link",
123+
("Link", "History"),
119124
)
120125

121126

0 commit comments

Comments
 (0)