dioxus_document/elements/title.rs
1use crate::document;
2
3use super::*;
4
5#[derive(Clone, Props, PartialEq)]
6pub struct TitleProps {
7 /// The contents of the title tag. The children must be a single text node.
8 children: Element,
9}
10
11/// Render the title of the page. On web renderers, this will set the [title](crate::elements::title) in the head. On desktop, it will set the window title.
12///
13/// Unlike most head components, the Title can be modified after the first render. Only the latest update to the title will be reflected if multiple title components are rendered.
14///
15///
16/// The children of the title component must be a single static or formatted string. If there are more children or the children contain components, conditionals, loops, or fragments, the title will not be updated.
17///
18/// # Example
19///
20/// ```rust, no_run
21/// # use dioxus::prelude::*;
22/// fn App() -> Element {
23/// rsx! {
24/// // You can use the Title component to render a title tag into the head of the page or window
25/// document::Title { "My Page" }
26/// }
27/// }
28/// ```
29#[component]
30#[doc(alias = "<title>")]
31pub fn Title(props: TitleProps) -> Element {
32 let children = props.children;
33 let text = match extract_single_text_node(&children) {
34 Ok(text) => text,
35 Err(err) => {
36 err.log("Title");
37 return VNode::empty();
38 }
39 };
40
41 // Update the title as it changes. NOTE: We don't use use_effect here because we need this to run on the server
42 let document = use_hook(document);
43 let last_text = use_hook(|| {
44 // Set the title initially
45 document.set_title(text.clone());
46 Rc::new(RefCell::new(text.clone()))
47 });
48
49 // If the text changes, update the title
50 let mut last_text = last_text.borrow_mut();
51 if text != *last_text {
52 document.set_title(text.clone());
53 *last_text = text;
54 }
55
56 VNode::empty()
57}