Adding an SEO Component
Every site on the web has basic meta-tags like the title, favicon or description of the page in their <head>
element. This information gets displayed in the browser and is used when someone shares your website, e.g. on Twitter. You can give your users and these websites additional data to embed your website with more data — and that’s where this guide for a SEO component comes in. At the end you’ll have a component you can place in your layout file and have rich previews for other clients, smartphone users, and search engines.
Note: This component will use useStaticQuery
. If you’re unfamiliar with that, have a look at the useStaticQuery documentation. You also have to have react-helmet
installed for which you can have a look at this document.
gatsby-config.js
Gatsby automatically exposes the siteMetadata
section of the gatsby-config
file in the GraphQL datalayer. It’s considered best practice to place your site meta information there.
SEO component
First create a new component with this initial boilerplate.
Note: propTypes
are included in this example to help you ensure you’re getting all the data you need in the component, and to help serve as a guide while destructuring / using those props.
As the SEO component should also be usable in other files, e.g. a template file, the component also accepts properties for which you set sensible defaults in the SEO.defaultProps
section. This way the information you put into siteMetadata
gets used every time unless you define the property explicitly.
Now define the query and pass it to useStaticQuery
. You can also alias query items, so title
gets renamed to defaultTitle
.
The next step is to destructure the data from the query and create an object that checks if the props were used. If not, the default values are applied. Aliasing the properties comes in handy here to avoid name collisions.
The last step is to return this data with the help of Helmet
. Your complete SEO component should look like this.
Examples
You could also put the Facebook and Twitter meta-tags into their own components, add custom favicons you placed in your static
folder, and add schema.org data (Google will use that for their Structured Data). To see how that works you can have a look at these two examples:
As mentioned at the beginning you are also able to use the component in templates, like in this example.