client_side_routing.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """Handle dynamic routes in static exports via client-side routing.
  2. Works with /utils/client_side_routing.js to handle the redirect and state.
  3. When the user hits a 404 accessing a route, redirect them to the same page,
  4. setting a reactive state var "routeNotFound" to true if the redirect fails. The
  5. `wait_for_client_redirect` function will render the component only after
  6. routeNotFound becomes true.
  7. """
  8. from __future__ import annotations
  9. from reflex import constants
  10. from reflex.components.component import Component
  11. from reflex.components.core.cond import cond
  12. from reflex.vars.base import Var
  13. route_not_found: Var = Var(_js_expr=constants.ROUTE_NOT_FOUND)
  14. class ClientSideRouting(Component):
  15. """The client-side routing component."""
  16. library = "$/utils/client_side_routing"
  17. tag = "useClientSideRouting"
  18. def add_hooks(self) -> list[str | Var]:
  19. """Get the hooks to render.
  20. Returns:
  21. The useClientSideRouting hook.
  22. """
  23. return [f"const {constants.ROUTE_NOT_FOUND} = {self.tag}()"]
  24. def render(self) -> str:
  25. """Render the component.
  26. Returns:
  27. Empty string, because this component is only used for its hooks.
  28. """
  29. return ""
  30. def wait_for_client_redirect(component: Component) -> Component:
  31. """Wait for a redirect to occur before rendering a component.
  32. This prevents the 404 page from flashing while the redirect is happening.
  33. Args:
  34. component: The component to render after the redirect.
  35. Returns:
  36. The conditionally rendered component.
  37. """
  38. return cond(
  39. route_not_found,
  40. component,
  41. ClientSideRouting.create(),
  42. )
  43. def default_404_page() -> Component:
  44. """Render the default 404 page.
  45. Returns:
  46. The 404 page component.
  47. """
  48. import reflex as rx
  49. return rx.el.span("404: Page not found")