Solid Meta

repository·main·Indexed 41 days ago

https://github.com/solidjs/solid-meta

An asynchronous, SSR-ready document head management library for SolidJS. It allows developers to declaratively manage <title>, <meta>, <link>, and other head tags from anywhere within their component hierarchy using components like <MetaProvider />, <Title />, <Meta />, <Style />, <Link />, and <Base />, or the useHead hook.

Tokens
2.2K
Snippets
8
Records
10
Agent score
50%

What's inside Solid Meta

  1. How MetaProvider manages head tags

    main

    The MetaProvider uses a context-based system to track tags.

    • Cascading Tags: Tags like <title> and <meta> are treated as 'cascading'. This means if multiple components attempt to set the same title or meta property, the library manages them as singletons or handles their priority/ordering to prevent duplicate or conflicting entries in the head.
    • Lifecycle: When a component using a meta component mounts, the tag is added to the <head>. When the component unmounts, the tag is automatically removed.
    • SSR Support: On the server, MetaProvider collects all tags rendered during the component tree traversal and uses useAssets to ensure they are included in the final HTML output.
  2. How Solid Meta works

    main

    Solid Meta allows you to define document.head tags anywhere in your component hierarchy.

    Core Workflow:

    1. Wrap your application with <MetaProvider />.
    2. Use components like <Title />, <Meta />, <Style />, <Link />, and <Base /> within your component tree to inject tags.
    3. On the Server: Tags are collected during rendering. If you are rendering the <head> element using SolidJS in JSX, it works automatically. Otherwise, use getAssets from solid-js/web to insert the collected assets into your HTML template.
    4. On the Client: The client-side runtime removes the server-generated tags and replaces them with client-rendered tags to ensure Single Page Application (SPA) navigation works correctly.
    IMPORTANT

    Do not use standard <title /> tags in any server files (e.g., entry-server.jsx|tsx or other server-side files), as they will override the functionality of @solidjs/meta.

  3. Configure Server-Side Rendering (SSR) with MetaProvider

    main

    When performing manual SSR, wrap your application with <MetaProvider />. Use getAssets() from solid-js/web to retrieve the collected tags and inject them into the <head> section of your HTML response.

    import { renderToString, getAssets } from 'solid-js/web';
    import { MetaProvider } from '@solidjs/meta';
    import App from './App';
    
    // ... within the context of a request ...
    const app = renderToString(() =>
      <MetaProvider>
        <App />
      </MetaProvider>
    );
    
    res.send(`
      <!doctype html>
      <html>
        <head>
          ${getAssets()}
        </head>
        <body>
          <div id="root">${app}</div>
        </body>
      </html>
    `);
  4. Configure SolidStart with MetaProvider

    main

    To use Solid Meta in a SolidStart project, wrap your app with <MetaProvider /> inside the root prop of the <Router /> component. You can optionally provide a default fallback title by placing a <Title /> component inside the <MetaProvider />.

    // @refresh reload
    import { MetaProvider, Title } from "@solidjs/meta";
    import { Router } from "@solidjs/router";
    import { FileRoutes } from "@solidjs/start";
    import { Suspense } from "solid-js";
    import "./app.css";
    
    export default function App() {
      return (
        <Router
          root={props => (
            <MetaProvider>
              <Title>SolidStart - Basic</Title>
              <a href="/">Index</a>
              <a href="/about">About</a>
              <Suspense>{props.children}</Suspense>
            </MetaProvider>
          )}
        >
          <FileRoutes />
        </Router>
      );
    }
  5. Setup MetaProvider to manage document head tags

    main

    To use any of the meta management components, you must wrap your application (or a relevant part of your component tree) in the MetaProvider component. This provider manages the lifecycle of tags like <title>, <meta>, <link>, and <style> in the document <head>, ensuring they are added and removed correctly during component mounting and unmounting, both on the client and during SSR.

    import { MetaProvider } from "@solidjs/meta";
    
    function App() {
      return (
        <MetaProvider>
          <YourAppContent />
        </MetaProvider>
      );
    }
  6. Use head tag components on the client

    main

    On the client side, simply render the desired head tag components within a <MetaProvider /> context to inject them into the <head>.

    import { MetaProvider, Title, Link, Meta } from '@solidjs/meta';
    
    const App = () => (
      <MetaProvider>
        <div class="Home">
          <Title>Title of page</Title>
          <Link rel="canonical" href="http://solidjs.com/" />
          <Meta name="example" content="whatever" />
          // ...
        </div>
      </MetaProvider>
    );
  7. Use the useHead hook for custom tags

    main

    If you need to manage tags that aren't covered by the high-level components, you can use the useHead hook. You must provide a TagDescription object containing the tag name and its props.

    import { useHead } from "@solidjs/meta";
    
    function CustomComponent() {
      useHead({
        tag: "script",
        props: { src: "https://example.com/script.js", async: true }
      });
      return null;
    }
  8. Use Title, Meta, Style, Link, and Base components

    main

    Solid Meta provides specialized components to declaratively manage head elements. These components use the useHead hook internally to register themselves with the MetaProvider.

    import { Title, Meta, Style, Link, Base, Stylesheet } from "@solidjs/meta";
    
    function MyComponent() {
      return (
        <>
          <Title>My Page Title</Title>
          <Meta name="description" content="This is my page description" />
          <Meta property="og:title" content="Social Media Title" />
          <Style>{`body { background: red; }`}</Style>
          <Link rel="canonical" href="https://example.com" />
          <Base href="/" />
          <Stylesheet href="/styles.css" />
        </>
      );
    }
  9. Reference: Meta management components

    main

    The following components are exported for managing specific HTML head elements. They accept standard JSX attributes for their respective elements.

    export const Title: Component<JSX.HTMLAttributes<HTMLTitleElement>>
    export const Style: Component<JSX.StyleHTMLAttributes<HTMLStyleElement>>
    export const Meta: Component<JSX.MetaHTMLAttributes<HTMLMetaElement>>
    export const Link: Component<JSX.LinkHTMLAttributes<HTMLLinkElement>>
    export const Base: Component<JSX.BaseHTMLAttributes<HTMLBaseElement>>
    export const Stylesheet: Component<Omit<JSX.LinkHTMLAttributes<HTMLLinkElement>, "rel">
    
    // Note: Stylesheet is a specialized Link component with rel="stylesheet" pre-applied.