Hands-On Full-Stack Web Development with GraphQL and React
上QQ阅读APP看书,第一时间看更新

Controlling document heads with React Helmet

When developing a web application, it is crucial that you can control your document heads. You might want to change the title or description, based on the content you are presenting.

React Helmet is a great package that offers this on the fly, including overriding multiple headers and server-side rendering.

Install it with the following command:

npm install --save react-helmet

You can add all standard HTML headers with React Helmet.

I recommend keeping standard head tags inside your template. They have the advantage that, before React has rendered, there is always the default document head. For our case, you can directly apply a title and description in App.js.

Import react-helmet at the top of the file:

import { Helmet } from 'react-helmet';

Add Helmet itself directly above postForm div:

<Helmet>
<title>Graphbook - Feed</title>
<meta name="description" content="Newsfeed of all your friends on
Graphbook" />
</Helmet>

If you reload the browser and watch the title on the tab bar of your browser carefully, you will see that it changes from Graphbook to Graphbook - Feed. This behavior happens because we already defined a title inside index.html. When React finishes rendering, the new document head is applied.