dioxus_retrouter/components/redirect.rs
1use dioxus::prelude::*;
2
3use crate::use_router;
4
5/// The props for the [`Router`](fn.Router.html) component.
6#[derive(Props)]
7pub struct RedirectProps<'a> {
8 /// The route to link to. This can be a relative path, or a full URL.
9 ///
10 /// ```rust, ignore
11 /// // Absolute path
12 /// Redirect { from: "", to: "/home" }
13 ///
14 /// // Relative path
15 /// Redirect { from: "", to: "../" }
16 /// ```
17 pub to: &'a str,
18
19 /// The route to link from. This can be a relative path, or a full URL.
20 ///
21 /// ```rust, ignore
22 /// // Absolute path
23 /// Redirect { from: "", to: "/home" }
24 ///
25 /// // Relative path
26 /// Redirect { from: "", to: "../" }
27 /// ```
28 pub from: Option<&'a str>,
29}
30
31/// If this component is rendered, it will redirect the user to the given route.
32///
33/// It will replace the current route rather than pushing the current one to the stack.
34pub fn Redirect<'a>(cx: Scope<'a, RedirectProps<'a>>) -> Element {
35 let router = use_router(cx);
36
37 let immediate_redirect = cx.use_hook(|| {
38 if let Some(from) = cx.props.from {
39 router.register_total_route(from.to_string(), cx.scope_id());
40 false
41 } else {
42 true
43 }
44 });
45
46 if *immediate_redirect || router.should_render(cx.scope_id()) {
47 router.replace_route(cx.props.to, None, None);
48 }
49
50 cx.render(rsx!(()))
51}