Skip to main content

dioxus_document/elements/
meta.rs

1use super::*;
2use crate::document;
3use dioxus_core::{VNode, use_hook};
4
5#[non_exhaustive]
6/// Props for the [`Meta`] component
7#[derive(Clone, Props, PartialEq)]
8pub struct MetaProps {
9    pub property: Option<String>,
10    pub name: Option<String>,
11    pub charset: Option<String>,
12    pub http_equiv: Option<String>,
13    pub content: Option<String>,
14    pub data: Option<String>,
15    #[props(extends = meta, extends = GlobalAttributes)]
16    pub additional_attributes: Vec<Attribute>,
17}
18
19impl MetaProps {
20    /// Get all the attributes for the meta tag
21    pub fn attributes(&self) -> Vec<(&'static str, String)> {
22        let mut attributes = Vec::new();
23        extend_attributes(&mut attributes, &self.additional_attributes);
24        if let Some(property) = &self.property {
25            attributes.push(("property", property.clone()));
26        }
27        if let Some(name) = &self.name {
28            attributes.push(("name", name.clone()));
29        }
30        if let Some(charset) = &self.charset {
31            attributes.push(("charset", charset.clone()));
32        }
33        if let Some(http_equiv) = &self.http_equiv {
34            attributes.push(("http-equiv", http_equiv.clone()));
35        }
36        if let Some(content) = &self.content {
37            attributes.push(("content", content.clone()));
38        }
39        if let Some(data) = &self.data {
40            attributes.push(("data", data.clone()));
41        }
42        attributes
43    }
44}
45
46/// Render a [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/meta) tag into the head of the page.
47///
48/// # Example
49///
50/// ```rust, no_run
51/// # use dioxus::prelude::*;
52/// fn RedirectToDioxusHomepageWithoutJS() -> Element {
53///     rsx! {
54///         // You can use the meta component to render a meta tag into the head of the page
55///         // This meta tag will redirect the user to the dioxuslabs homepage in 10 seconds
56///         document::Meta {
57///             http_equiv: "refresh",
58///             content: "10;url=https://dioxuslabs.com",
59///         }
60///     }
61/// }
62/// ```
63///
64/// <div class="warning">
65///
66/// Any updates to the props after the first render will not be reflected in the head.
67///
68/// </div>
69#[component]
70#[doc(alias = "<meta>")]
71pub fn Meta(props: MetaProps) -> Element {
72    use_update_warning(&props, "Meta {}");
73
74    use_hook(|| {
75        let document = document();
76        let insert_link = document.create_head_component();
77
78        if !insert_link {
79            return;
80        }
81
82        document.create_meta(props);
83    });
84
85    VNode::empty()
86}