dioxus_retrouter/components/
route.rs

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