React Helmet

How to Use React Helmet – With Example

React Helmet is a popular library in the React ecosystem that allows you to manage document head tags (such as title, meta, link, etc.) in a React application. It’s particularly useful when you need to dynamically update the head of your document based on the content of your React components.

Here’s a step-by-step guide on how to use React Helmet with an example use case:

Installation:

Start by installing React Helmet using npm or yarn:

npm install react-helmet
# or
yarn add react-helmet

Import React Helmet:

Import `Helmet` from `react-helmet-async` in your component where you want to manage head tags.

import { Helmet } from 'react-helmet-async';

Usage:

Wrap your component content with `Helmet` tags, and then use the `title` and other components inside to update head tags.

import React from 'react';
import { Helmet } from 'react-helmet-async';

const ExampleComponent = () => {
  return (
    <div>
      <Helmet>
        <title>Your Page Title</title>
        <meta name="description" content="This is a description." />
        <link rel="canonical" href="http://example.com/page" />
      </Helmet>

      {/* Your component content goes here */}
      <h1>Hello, React Helmet!</h1>
    </div>
  );
};

export default ExampleComponent;

Dynamic Head Content:

React Helmet is particularly useful for dynamically updating head content based on your component’s state or props. For example:

import React, { useState } from 'react';
import { Helmet } from 'react-helmet-async';

const DynamicTitleComponent = () => {
  const [pageTitle, setPageTitle] = useState('Default Title');

  const handleTitleChange = () => {
    setPageTitle('New Page Title');
  };

  return (
    <div>
      <Helmet>
        <title>{pageTitle}</title>
      </Helmet>

      <h1>{pageTitle}</h1>
      <button onClick={handleTitleChange}>Change Title</button>
    </div>
  );
};

export default DynamicTitleComponent;

In this example, clicking the “Change Title” button will update both the displayed title and the actual HTML document title.

Server-Side Rendering (SSR):

If you’re working with server-side rendering (SSR), use `HelmetProvider` from `react-helmet-async` to wrap your app component.

import React from 'react';
import { HelmetProvider } from 'react-helmet-async';
import App from './App';

const Root = () => (
  <HelmetProvider>
    <App />
  </HelmetProvider>
);

export default Root;

This ensures that the document head tags are correctly managed during server-side rendering.

Remember to customize the head tags based on your specific requirements, and React Helmet will handle the rest for you. It’s a powerful tool for managing SEO, social sharing, and other aspects of your application that rely on the document head.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top