dioxus_router/components/
router.rs

1use dioxus_lib::prelude::*;
2
3use std::str::FromStr;
4
5use crate::{
6    prelude::{provide_router_context, Outlet},
7    routable::Routable,
8    router_cfg::RouterConfig,
9};
10
11/// The props for [`Router`].
12#[derive(Props)]
13pub struct RouterProps<R: Clone + 'static> {
14    #[props(default, into)]
15    config: Callback<(), RouterConfig<R>>,
16}
17
18impl<T: Clone> Clone for RouterProps<T> {
19    fn clone(&self) -> Self {
20        *self
21    }
22}
23
24impl<T: Clone> Copy for RouterProps<T> {}
25
26impl<R: Clone + 'static> Default for RouterProps<R> {
27    fn default() -> Self {
28        Self {
29            config: Callback::new(|_| RouterConfig::default()),
30        }
31    }
32}
33
34impl<R: Clone> PartialEq for RouterProps<R> {
35    fn eq(&self, _: &Self) -> bool {
36        // prevent the router from re-rendering when the initial url or config changes
37        true
38    }
39}
40
41/// A component that renders the current route.
42pub fn Router<R: Routable + Clone>(props: RouterProps<R>) -> Element
43where
44    <R as FromStr>::Err: std::fmt::Display,
45{
46    use crate::prelude::{outlet::OutletContext, RouterContext};
47
48    use_hook(|| {
49        provide_router_context(RouterContext::new(props.config.call(())));
50
51        provide_context(OutletContext::<R> {
52            current_level: 0,
53            _marker: std::marker::PhantomData,
54        });
55    });
56
57    rsx! { Outlet::<R> {} }
58}