diff --git a/packages/router/src/hooks/use_router.rs b/packages/router/src/hooks/use_router.rs index 5afea5cccb..b78c0f9e58 100644 --- a/packages/router/src/hooks/use_router.rs +++ b/packages/router/src/hooks/use_router.rs @@ -12,3 +12,9 @@ pub fn use_router() -> RouterContext { pub fn router() -> RouterContext { dioxus_lib::prelude::consume_context() } + +/// Try to acquire the router without subscribing to updates. +#[doc(alias = "url")] +pub fn try_router() -> Option { + dioxus_lib::prelude::try_consume_context() +} diff --git a/packages/router/src/navigation.rs b/packages/router/src/navigation.rs index 0c78c42b8b..cd331122fb 100644 --- a/packages/router/src/navigation.rs +++ b/packages/router/src/navigation.rs @@ -7,7 +7,9 @@ use std::{ use url::{ParseError, Url}; -use crate::{components::child_router::consume_child_route_mapping, routable::Routable, router}; +use crate::{ + components::child_router::consume_child_route_mapping, hooks::try_router, routable::Routable, +}; impl From for NavigationTarget { fn from(value: R) -> Self { @@ -94,20 +96,24 @@ impl From for NavigationTarget { impl From<&str> for NavigationTarget { fn from(value: &str) -> Self { - let router = router(); - match router.internal_route(value) { - true => NavigationTarget::Internal(value.to_string()), - false => NavigationTarget::External(value.to_string()), + match try_router() { + Some(router) => match router.internal_route(value) { + true => NavigationTarget::Internal(value.to_string()), + false => NavigationTarget::External(value.to_string()), + }, + None => NavigationTarget::External(value.to_string()), } } } impl From for NavigationTarget { fn from(value: String) -> Self { - let router = router(); - match router.internal_route(&value) { - true => NavigationTarget::Internal(value), - false => NavigationTarget::External(value), + match try_router() { + Some(router) => match router.internal_route(&value) { + true => NavigationTarget::Internal(value), + false => NavigationTarget::External(value), + }, + None => NavigationTarget::External(value.to_string()), } } }