Skip to content

Commit b83bb4c

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

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-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

+9-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

@@ -54,9 +55,12 @@ def router_component(
5455

5556
if match is not None:
5657
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),
58+
return html._(
59+
ConnectionContext(
60+
_route_state_context(element, value=_RouteState(set_location, params)),
61+
value=Connection(old_conn.scope, location, old_conn.carrier),
62+
),
63+
_history({"on_change": lambda event: set_location(Location(**event))}),
6064
)
6165

6266
return None
@@ -113,9 +117,9 @@ def _match_route(
113117
return None
114118

115119

116-
_link = export(
120+
_link, _history = export(
117121
module_from_file("reactpy-router", file=Path(__file__).parent / "bundle.js"),
118-
"Link",
122+
("Link", "History"),
119123
)
120124

121125

0 commit comments

Comments
 (0)