This website is a work in progress.

Handle pages meta (HTML <head>)

Handle pages meta (HTML <head>)

The recommended way to manage HTML meta tags (title, description, links, external scripts/styles, facebook & twitter meta...) is to use react-helmet package.

This reusable React component will manage all of your changes to the document head. It takes plain HTML tags and outputs plain HTML tags.

⚠️ You can even define <html> and <body> attributes.

First, install react-helmet

npm install --save react-helmet

You can start using react-helmet directly in any components:

import Head from "react-helmet";
import {
  createApp,
  withPhenomicApi,
  query,
  BodyRenderer,
  textRenderer,
} from "@phenomic/preset-react-app/lib/client";
 
// ...
 
const Home = ({ isLoading, posts }) => (
  <div>
    <Head>
      <title>Hello world</title>
      <meta name="description" content="Everything is awesome!" />
    </Head>
    <h1>Home</h1>
    {!isLoading && <ul>{/* ... */}</ul>}
  </div>
);
 
// ...
 
const BlogPost = ({ isLoading, page }) => (
  <div>
    {isLoading && "Loading..."}
    {!isLoading &&
      page.node && (
        <article>
          <Head>
            <title>{page.node.title}</title>
            <meta
              name="description"
              content={textRenderer(page.node.body).slice(0, 150) + ""}
            />
          </Head>
          <h1>{page.node.title}</h1>
          <BodyRenderer>{page.node.body}</BodyRenderer>
        </article>
      )}
    <footer>{/* ... */}</footer>
  </div>
);

In order to have the injection of meta into your static html files, you will need a custom html template.

⚠️ Default Html component is very rudimentary and should be adapted if you care about SEO.

Here is what you need to add if you want to include all react-helmet output:

// Html.js
export default ({ App, render }) => {
  // if needed, you can know if you are in development or in static rendering
  // const isDev = process.env.PHENOMIC_ENV === "development"
  const { Main, State, Script, Style } = render(<App />);
  const helmet = Head.renderStatic();
  return (
    <html {...helmet.htmlAttributes.toComponent()}>
      <head>
        {helmet.meta.toComponent()}
        {helmet.title.toComponent()}
        {helmet.base.toComponent()}
        <Style />
        {helmet.link.toComponent()}
        {helmet.style.toComponent()}
        {helmet.script.toComponent()}
        {helmet.noscript.toComponent()}
      </head>
      <body {...helmet.bodyAttributes.toComponent()}>
        <Main />
        <State />
        <Script />
      </body>
    </html>
  );
};

This file Html.js file should be placed next to App.js

Now your static render should include all meta generated by react-helmet.

To know more about all the things you can do with react-helmet, please read the documentation.


Continue tutorial