Overview
The frontend-head
package exposes the Head
component that allows appending elements to your store's <head>
.
📘 Elements that should stay present in the head
between page changes should be added to the Head
component inside the PageMeta
section.
Import
frontend-head
is already pre-installed on every Shogun Frontend store. To import:
import Head from 'frontend-head'
Usage
Below is a basic example of the Head
from PageMeta
that is pre-installed on every Shogun Frontend store.
Head
accepts the elements through the children
prop.
PageMeta.js
import React from 'react'
import Head from 'frontend-head'
const PageMeta = ({ title, description, url }) => {
return (
<Head>
{title && <title>{title}</title>}
{description && <meta name="description" content={description} />}
<meta name="viewport" content="width=device-width, initial-scale=1" />
{url && <link rel="canonical" href={url} key="canonicalURL" />}
</Head>
)
}
export default PageMeta
Duplicating elements
Head
component can be used throughout the application and as a result, it is possible to add duplicate elements to the head
.
Head
will remove duplicate title
elements and any meta
elements that have a name
attribute. To prevent the deduplication of other elements you should use the key
prop.
Head
will take the element furthest down the component hierarchy when it detects a duplicate. In the example below, the meta viewport that will be rendered is on line 11.
PageMeta.js
import React from 'react'
import Head from 'frontend-head'
const PageMeta = ({ title, description, url }) => {
return (
<Head>
{title && <title>{title}</title>}
{description && <meta name="description" content={description} />}
{/* The following meta tag will NOT be rendered */}
<meta name="viewport" content="width=device-width, initial-scale=0" />
{url && <link rel="canonical" href={url} key="canonicalURL" />}
{/* The following meta tag will be rendered */}
<meta name="viewport" content="width=device-width, initial-scale=1" />
</Head>
)
}
export default PageMeta
Nesting
title, meta or any other elements (e.g. script) need to be contained as direct children of the Head element, or wrapped into maximum one level of <React.Fragment> or arrays—otherwise the tags won't be correctly picked up on client-side navigations.
Scripts
To add a scripts we recommend using Script
in your components, instead of manually creating a <script>
in Head
.
Default elements
By default, the canonical URL is added as shown in the examples above. To override, add the element with the corresponding key
(canonicalURL
) prop and it will be deduplicated.