dioxus_document/elements/
title.rs

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