$ ls ~yifei/notes/

React Helmet

Posted on:

Last modified:

React Helmet 用来在 React 程序中更改 header 的内容。

import React from "react";
import "./styles.css";

import { Helmet } from "react-helmet";

export default function App() {
  return (
    <div>
      <Helmet htmlAttributes>
        <html lang="en" />
        <title>Hello from React Helmet</title>
        <meta name="description" content="Basic example" />
      </Helmet>
      
      <div className="App">
        <h1>React Helmet Basic Example</h1>
      </div>
    </div>
  );
}

React helmet 支持 html, body 和 head 中的 title, base, meta, link, script, noscript, 和 style 标签。

尽量不要用 helmet 去加载 script 和 style,有更好的解决方案。

奇怪的 bug

在元素中直接使用 html 字符串拼接会报错,使用 JS 的字符串差值就可以,醉了。

Helmet expects a string as a child of <title>

<Helmet>
    <title>Product - { item.name }</title>
</Helmet>

// 改成

<Helmet>
    <title>{ `Product - ${ item.name }` }</title>
</Helmet>

参考

  1. https://www.newline.co/@dmitryrogozhny/when-to-use-and-when-to-avoid-using-react-helmet--bf6f62d5
  2. https://github.com/nfl/react-helmet/issues/274

© 2016-2022 Yifei Kong. Powered by ynotes

All contents are under the CC-BY-NC-SA license, if not otherwise specified.

Opinions expressed here are solely my own and do not express the views or opinions of my employer.