route.rs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. use crate::{RouteContext, RouterContext};
  2. use dioxus::prelude::*;
  3. /// Props for the [`Route`](struct.Route.html) component.
  4. #[derive(Props)]
  5. pub struct RouteProps<'a> {
  6. /// The path to match.
  7. pub to: &'a str,
  8. /// The component to render when the path matches.
  9. pub children: Element<'a>,
  10. }
  11. /// A component that conditionally renders children based on the current location.
  12. ///
  13. /// # Example
  14. ///
  15. ///```rust, ignore
  16. /// rsx!(
  17. /// Router {
  18. /// Route { to: "/home", Home {} }
  19. /// Route { to: "/about", About {} }
  20. /// Route { to: "/Blog", Blog {} }
  21. /// }
  22. /// )
  23. /// ```
  24. pub fn Route<'a>(cx: Scope<'a, RouteProps<'a>>) -> Element {
  25. let router_root = use_context::<RouterContext>(cx).unwrap();
  26. let root_context = use_context::<RouteContext>(cx);
  27. cx.use_hook(|| {
  28. // create a bigger, better, longer route if one above us exists
  29. let total_route = match root_context {
  30. Some(ctx) => ctx.total_route.clone(),
  31. None => cx.props.to.to_string(),
  32. };
  33. // provide our route context
  34. let route_context = cx.provide_context(RouteContext {
  35. declared_route: cx.props.to.to_string(),
  36. total_route,
  37. });
  38. // submit our rout
  39. router_root.register_total_route(route_context.total_route, cx.scope_id());
  40. });
  41. log::trace!("Checking Route: {:?}", cx.props.to);
  42. if router_root.should_render(cx.scope_id()) {
  43. log::trace!("Route should render: {:?}", cx.scope_id());
  44. cx.render(rsx!(&cx.props.children))
  45. } else {
  46. log::trace!("Route should *not* render: {:?}", cx.scope_id());
  47. cx.render(rsx!(()))
  48. }
  49. }