This is unreleased documentation for Yew Next version.
For up-to-date documentation, see the latest version on docs.rs.

yew_router/
hooks.rs

1//! Hooks to access router state and navigate between pages.
2
3use yew::prelude::*;
4
5use crate::history::*;
6use crate::navigator::Navigator;
7use crate::routable::Routable;
8use crate::router::{LocationContext, NavigatorContext};
9
10/// A hook to access the [`Navigator`].
11#[hook]
12pub fn use_navigator() -> Option<Navigator> {
13    use_context::<NavigatorContext>().map(|m| m.navigator())
14}
15
16/// A hook to access the current [`Location`].
17#[hook]
18pub fn use_location() -> Option<Location> {
19    Some(use_context::<LocationContext>()?.location())
20}
21
22/// A hook to access the current route.
23///
24/// This hook will return [`None`] if there's no available location or none of the routes match.
25///
26/// # Note
27///
28/// If your `Routable` has a `#[not_found]` route, you can use `.unwrap_or_default()` instead of
29/// `.unwrap()` to unwrap.
30#[hook]
31pub fn use_route<R>() -> Option<R>
32where
33    R: Routable + 'static,
34{
35    let navigator = use_navigator()?;
36    let location = use_location()?;
37    let path = navigator.strip_basename(location.path().into());
38
39    R::recognize(&path)
40}