Skip to content

Commit

Permalink
handle client-side history changes
Browse files Browse the repository at this point in the history
  • Loading branch information
rmorshea committed May 11, 2023
1 parent a6f7d23 commit d31f149
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
17 changes: 16 additions & 1 deletion js/src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from "react";
import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import htm from "htm";

Expand All @@ -15,6 +15,21 @@ export function bind(node, config) {
};
}

export function History({ onChange }) {
// capture changes to the browser's history
useEffect(() => {
const listener = () => {
onChange({
pathname: window.location.pathname,
search: window.location.search,
});
};
window.addEventListener("popstate", listener);
return () => window.removeEventListener("popstate", listener);
});
return null;
}

export function Link({ to, onClick, children, ...props }) {
const handleClick = (event) => {
event.preventDefault();
Expand Down
15 changes: 10 additions & 5 deletions reactpy_router/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from reactpy.core.types import VdomChild, VdomDict
from reactpy.types import ComponentType, Context, Location
from reactpy.web.module import export, module_from_file
from reactpy import html

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

Expand All @@ -44,6 +45,7 @@ def router_component(
) -> ComponentType | None:
old_conn = use_connection()
location, set_location = use_state(old_conn.location)
print(location)

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

if match is not None:
element, params = match
return ConnectionContext(
_route_state_context(element, value=_RouteState(set_location, params)),
value=Connection(old_conn.scope, location, old_conn.carrier),
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
Expand Down Expand Up @@ -113,9 +118,9 @@ def _match_route(
return None


_link = export(
_link, _history = export(
module_from_file("reactpy-router", file=Path(__file__).parent / "bundle.js"),
"Link",
("Link", "History"),
)


Expand Down

0 comments on commit d31f149

Please sign in to comment.