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

yew_router/
switch.rs

1//! The [`Switch`] Component.
2
3use yew::prelude::*;
4
5use crate::prelude::*;
6
7/// Props for [`Switch`]
8#[derive(Properties, PartialEq, Clone)]
9pub struct SwitchProps<R>
10where
11    R: Routable,
12{
13    /// Callback which returns [`Html`] to be rendered for the current route.
14    pub render: Callback<R, Html>,
15    #[prop_or_default]
16    pub pathname: Option<String>,
17}
18
19/// A Switch that dispatches route among variants of a [`Routable`].
20///
21/// When a route can't be matched, including when the path is matched but the deserialization fails,
22/// it looks for the route with `not_found` attribute.
23/// If such a route is provided, it redirects to the specified route.
24/// Otherwise `html! {}` is rendered and a message is logged to console
25/// stating that no route can be matched.
26/// See the [crate level document][crate] for more information.
27#[function_component]
28pub fn Switch<R>(props: &SwitchProps<R>) -> Html
29where
30    R: Routable + 'static,
31{
32    let route = use_route::<R>();
33
34    let route = props
35        .pathname
36        .as_ref()
37        .and_then(|p| R::recognize(p))
38        .or(route);
39
40    match route {
41        Some(route) => props.render.emit(route),
42        None => {
43            tracing::warn!("no route matched");
44            Html::default()
45        }
46    }
47}