react-helmet README

The project's README from github.com/nfl/react-helmet. As one markdown file: README.md.

React Helmet

npm Version codecov.io Build Status Dependency Status PRs Welcome

This reusable React component will manage all of your changes to the document head.

Helmet takes plain HTML tags and outputs plain HTML tags. It's dead simple, and React beginner friendly.

6.1.0 Major Changes

Example

import React from "react";
import {Helmet} from "react-helmet";

class Application extends React.Component {
  render () {
    return (
        <div className="application">
            <Helmet>
                <meta charSet="utf-8" />
                <title>My Title</title>
                <link rel="canonical" href="http://mysite.com/example" />
            </Helmet>
            ...
        </div>
    );
  }
};

Nested or latter components will override duplicate changes:

<Parent>
    <Helmet>
        <title>My Title</title>
        <meta name="description" content="Helmet application" />
    </Helmet>

    <Child>
        <Helmet>
            <title>Nested Title</title>
            <meta name="description" content="Nested component" />
        </Helmet>
    </Child>
</Parent>

outputs:

<head>
    <title>Nested Title</title>
    <meta name="description" content="Nested component">
</head>

See below for a full reference guide.

Features

Compatibility

Helmet 5 is fully backward-compatible with previous Helmet releases, so you can upgrade at any time without fear of breaking changes. We encourage you to update your code to our more semantic API, but please feel free to do so at your own pace.

Installation

Yarn:

yarn add react-helmet

npm:

npm install --save react-helmet

Server Usage

To use on the server, call Helmet.renderStatic() after ReactDOMServer.renderToString or ReactDOMServer.renderToStaticMarkup to get the head data for use in your prerender.

Because this component keeps track of mounted instances, you have to make sure to call renderStatic on server, or you'll get a memory leak.

ReactDOMServer.renderToString(<Handler />);
const helmet = Helmet.renderStatic();

This helmet instance contains the following properties:

Each property contains toComponent() and toString() methods. Use whichever is appropriate for your environment. For attributes, use the JSX spread operator on the object returned by toComponent(). E.g:

As string output

const html = `
    <!doctype html>
    <html ${helmet.htmlAttributes.toString()}>
        <head>
            ${helmet.title.toString()}
            ${helmet.meta.toString()}
            ${helmet.link.toString()}
        </head>
        <body ${helmet.bodyAttributes.toString()}>
            <div id="content">
                // React stuff here
            </div>
        </body>
    </html>
`;

As React components

function HTML () {
    const htmlAttrs = helmet.htmlAttributes.toComponent();
    const bodyAttrs = helmet.bodyAttributes.toComponent();

    return (
        <html {...htmlAttrs}>
            <head>
                {helmet.title.toComponent()}
                {helmet.meta.toComponent()}
                {helmet.link.toComponent()}
            </head>
            <body {...bodyAttrs}>
                <div id="content">
                    // React stuff here
                </div>
            </body>
        </html>
    );
}

Note: Use the same instance

If you are using a prebuilt compilation of your app with webpack in the server be sure to include this in the webpack file so that the same instance of react-helmet is used.

externals: ["react-helmet"],

Or to import the react-helmet instance from the app on the server.

Reference Guide

<Helmet
    {/* (optional) set to false to disable string encoding (server-only) */}
    encodeSpecialCharacters={true}

    {/*
        (optional) Useful when you want titles to inherit from a template:

        <Helmet
            titleTemplate="%s | MyAwesomeWebsite.com"
        >
            <title>Nested Title</title>
        </Helmet>

        outputs:

        <head>
            <title>Nested Title | MyAwesomeWebsite.com</title>
        </head>
    */}
    titleTemplate="MySite.com - %s"

    {/*
        (optional) used as a fallback when a template exists but a title is not defined

        <Helmet
            defaultTitle="My Site"
            titleTemplate="My Site - %s"
        />

        outputs:

        <head>
            <title>My Site</title>
        </head>
    */}
    defaultTitle="My Default Title"
    
    {/* (optional) set to false to not use requestAnimationFrame and instead update the DOM as soon as possible.
        Useful if you want to update the title when the tab is out of focus 
    */}
    defer={false}

    {/* (optional) callback that tracks DOM changes */}
    onChangeClientState={(newState, addedTags, removedTags) => console.log(newState, addedTags, removedTags)}
>
    {/* html attributes */}
    <html lang="en" amp />

    {/* body attributes */}
    <body className="root" />

    {/* title attributes and value */}
    <title itemProp="name" lang="en">My Plain Title or {`dynamic`} title</title>

    {/* base element */}
    <base target="_blank" href="http://mysite.com/" />

    {/* multiple meta elements */}
    <meta name="description" content="Helmet application" />
    <meta property="og:type" content="article" />

    {/* multiple link elements */}
    <link rel="canonical" href="http://mysite.com/example" />
    <link rel="apple-touch-icon" href="http://mysite.com/img/apple-touch-icon-57x57.png" />
    <link rel="apple-touch-icon" sizes="72x72" href="http://mysite.com/img/apple-touch-icon-72x72.png" />
    {locales.map((locale) => {
        <link rel="alternate" href="http://example.com/{locale}" hrefLang={locale} key={locale}/>
    })}

    {/* multiple script elements */}
    <script src="http://include.com/pathtojs.js" type="text/javascript" />

    {/* inline script elements */}
    <script type="application/ld+json">{`
        {
            "@context": "http://schema.org"
        }
    `}</script>

    {/* noscript elements */}
    <noscript>{`
        <link rel="stylesheet" type="text/css" href="foo.css" />
    `}</noscript>

    {/* inline style elements */}
    <style type="text/css">{`
        body {
            background-color: blue;
        }

        p {
            font-size: 12px;
        }
    `}</style>
</Helmet>

Contributing to this project

Please take a moment to review the guidelines for contributing.

License

MIT

react-helmet (nfl/react-helmet)

Searching Database…

这是什么?这是一个可复用的 React 组件,用来统一管理你对文档头部(document head)的所有修改——也就是 title、meta、link 和 script 这些位于应用渲染内容之外的标签。
它是放在 React 组件树里的组件,还是一个独立工具?是一个组件——你在 React 树的任意位置放进去,里面写普通的 HTML 标签,Helmet 就会把这些标签输出到 head 里。它刻意做得简单,对 React 初学者很友好。
怎么把它加到我的项目里?从 npm 或 Yarn 安装(npm install react-helmet),然后在需要的地方用这个组件把你的 head 标签包起来。
除了 React 之外还需要别的吗?只要有一个 React 应用就行——这个包本身只依赖几个小型辅助库(prop-types、react-side-effect、react-fast-compare、object-assign),npm 会自动帮你装好。
服务端渲染有什么坑?Helmet 会追踪已挂载的实例,所以在服务端你必须调用 renderStatic(),否则会造成内存泄漏。如果你的服务端包是用 webpack 预先打包的,要确保它和应用共享同一个 Helmet 实例。
它能管理哪些 head 标签?所有合法的 head 标签:title、base、meta、link、script、noscript 和 style。它还支持给 body、html 和 title 标签设置属性。
服务端渲染是怎么工作的?在执行 ReactDOMServer.renderToString 或 renderToStaticMarkup 之后,调用 Helmet.renderStatic()。你会得到一个对象,包含 title、meta、link、script、style、base、noscript 以及 body/html 的属性,每项都带有 toString() 和 toComponent() 方法,可以直接接入你的预渲染流程。
如果我的两个组件设置了同一个标签怎么办?嵌套的或后出现的组件会覆盖重复的 head 修改。不过在同一个组件里声明的重复项会保留下来,这正是你保留多个 'apple-touch-icon' 链接的方式。
我用的是老版本的 Helmet——升级会很麻烦吗?不会。Helmet 5 对之前的版本完全向后兼容,你可以随时升级,不会有破坏性改动;迁移到更新的、语义更清晰的 API 是推荐的,但不是强制的。
Creator
nfl
Size
2.1 MB
Stars
17.4K
Age
11y
Commits · 90 Days