3.0.6 • Published 3 years ago

@app-elements/helmet v3.0.6

Weekly downloads
162
License
ISC
Repository
github
Last release
3 years ago

Helmet

A very basic means of setting and updating document title and meta tags from your (P)React components.

Installation

npm install --save @app-elements/helmet

Usage

Helmet can be declared in your JSX many times. Each time, the result will be merged with the previous. It follows the order of your React tree, meaning the last (or "most nested") Helmet declared in your React tree will take precedence.

Say, in your root Component:

import Helmet from '@app-elements/helmet'

<Helmet
  title='Welcome'
  titleTemplate='PWA Starter | %s'
  defaultTitle='Welcome'
/>

Then, in some nested child Component:

<Helmet
  title='Nested Title'
/>

The resulting object representation would be:

{
  "title": "Nested Title",
  "titleTemplate": "PWA Starter | %s",
  "defaultTitle": "Welcome"
}

The document.title will be updated each time a Helmet instance is rendered. However, the meta tags are only rendered once (and still give precedence to the last Helmet in the tree). This means the meta tags are set properly on initial load and when rendering on the server. So, when you share a link on social media, the correct OG tags or other meta tags will be used. But, the meta tags will not update after initial load. From what I can tell, this has no negative affect.

Server-Side Rendering

You can see full working code in PWA Starter, but here are the key bits:

import render from 'preact-render-to-string'

import Helmet, {rewind} from '@app-elements/helmet'

const head = render(<Helmet {...rewind()} />).slice(5, -6) // slice off `<head>`, `</head>` tags

// ...
app.get('*', (req, res) => {
  /// ...
  res.send(`
    <html lang="en">
      <head>
        <base href="/">
        <meta charset="utf-8">
        <link rel="stylesheet" href="./bundle.css" />
        ${head}
      </head>
      <body>
        <div class='main-app-container'>${html}</div>
        <script>window.__initial_store__ = ${JSON.stringify(state)};</script>
        <script src="./bundle.js"></script>
      </body>
    </html> 
  `) 
})

Props

PropTypeDefaultDescription
titleStringNoneThe title to set. Will be used inside the titleTemplate string.
titleTemplateString'%s'Format your title strings. %s will be replaced with current title. Ex. '%s | My Cool Site'
defaultTitleStringNoneThe default value to replace %s with in your titleTemplate. Ex. 'Home'
metaArrayNoneAn array of objects representing <meta /> tags. Supports name, property, content attributes.
3.0.6

3 years ago

3.0.4

4 years ago

3.0.5

4 years ago

3.0.3

4 years ago

3.0.2

4 years ago

3.0.1

4 years ago

3.0.0

4 years ago

3.0.0-alpha.0

4 years ago

2.1.0

5 years ago

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

6 years ago