What is React Helmet?

For React-based apps, React Helmet serves as the document head manager. It makes it very simple for developers to change meta tags on both the server-side and client-side. This library is suitable for applications that require a high level of SEO. It’s also a media-friendly library with a variety of dependencies and features that make using it in any React app simple. In this article, we’ll go over all of the details and show you how to include React Helmet into your project.

Every web developer wishes for his or her website to appear at the top of a browser’s search results pages. Unfortunately, there are times when the search engine crawler fails to deliver accurate results. This issue arises due to the browser’s inability to display JavaScript. This implies that search engine crawlers will not prefer SPAs built on the React or Angular platforms. This is one of the most critical challenges that web developers face when it comes to getting their sites to the top of the page. As a result, Server Side Rendering may be utilize to fix the problem, although it has limits in terms of adaptability. React Helmet comes to the rescue in this situation.

Setup of React Helmet Using npm

Before we go any further, we’ll need to install React Helmet using the traditional and most effective npm approach. We’ll first use some commands to create a new React project, then begin the development process after the server is ready.

Use the commands below to install and initialize React Helmet.

npx create-react-app react-helmet 
cd react-helmet  
npm start  

Ensure that the system port 3000 is occupied, and you’ll be good to go. Open http://localhost:3000 to check out your app.

Newly Created React App

We might have known that, like other SPAs, our application would have a default <head> element. If we go to the browser for a closer look, we can easily verify this by pressing F12 in Chrome or Ctrl+Shift+C in Firefox. We can examine what the <head> element looks like by analyzing the content in Chrome.

<head>  
    <meta charset="utf-8">  
    <link rel="icon" href="/favicon.ico">  
    <meta name="viewport" content="width=device-width, initial-scale=1">  
    <meta name="theme-color" content="#000000">  
    <meta name="description" content="Web site created using create-react-app">  
    <link rel="apple-touch-icon" href="/logo192.png">  
  
    <link rel="manifest" href="/manifest.json">  
  
    <title>React App</title>  
  <style type="text/css">  
   <!-- CSS -->  
  </style>  
</head> 

There’s an alternative approach to deal with the <head>. This is accomplish by modifying the public/index.html directory. Although this should not be use as a preferred method because it is inefficient. After that, we’ll need to install React Helmet and utilize it in our app.

Installation and Setup

The command below is use to install React Helmet into your React project – Yarn or npm.

npm install react-helmet   

OR

yarn add react-helmet

After that, follow the instructions for importing the Helmet component. After that, we can easily add items to the document’s <head>. In the code sample below, you can see how the next step is perform. /src/App.js

// src/App.js  
  
import React from "react";  
import "./App.css";  
import { Helmet } from "react-helmet";  
  
function App() {  
  return (  
    <div className="App">  
  
      <Helmet>  
        <html lang="en" />  
        <title>React Helmet</title>  
        <meta name="description" content="Concept of React Helmet" />  
        <meta name="theme-color" content="#E6E6FA" />  
      </Helmet>  
  
      <header className="App-header">Title will be React Helmet</header>  
    </div>  
  );  
}  
export default App; 

We will observe changes in our React application as soon as the above code snippet is modified to the directory src/App.js file.

We’ve used only the <title>, <html>, and <meta> tag elements for description in this code snippet to keep things simple, and we’ve utilized some theme color for the other components like base, meta, link, script, and so on. These components are commonly refer to as Helmet’s children. The characteristics that are define for the body tag and Html tag are shows in the example below.

 <Helmet>  
        {/* html attributes */}  
        <html lang="en" />  
  
        {/* body attributes */}  
        <body className="dark" />  
  
        {/* title element */}  
        <title>React Helmet</title>  
  
        {/* base element */}  
        <base target="_blank" href="https://softhunt.net/" />  
  
        {/* meta elements */}  
        <meta name="description" content="Concept of React Helmet" />  
  
        <meta name="theme-color" content="#E6E6FA" />  
  
        {/* link elements */}  
        <link rel="canonical" href="https://softhunt.net/" />  
</Helmet>  

Now create a Child.js file to be more specific, the child component is given priority. Consider the code below:

// src/Child.js  
  
import React from "react";  
import { Helmet } from "react-helmet";  
function Child() {  
  return (  
    <div>  
      <Helmet>  
        <title>Child Component</title>  
      </Helmet>  
     {"  "}Title will be Child Component  
    </div>  
  );  
}  
export default Child;  

Now, in order to import the child component, namely the Child.js file, into the parent component, namely the App.js file. We must remember to alter the document’s title to match the child component. It’s also important to keep in mind that the metadata and theme color can’t be change. The code snippet below is an example of how to accomplish this.

// src/App.js  
  
import React from "react";  
import "./App.css";  
import { Helmet } from "react-helmet";  
import Child from "./Child";  
  
function App() {  
  return (  
    <div className="App">  
  
      <Helmet>  
        <html lang="en" />  
        <title>React Helmet</title>  
        <meta name="description" content="Concept of React Helmet" />  
        <meta name="theme-color" content="#E6E6FA" />  
      </Helmet>  
  
      <header className="App-header">
      Title will not be React Helmet
      <Child />  
      </header>  
    </div>  
  );  
}  
export default App; 

Another point to remember is that between two child components, the one that occurs later will always be assign the most priority. For instance, consider two child components <Child1> and <Child2>, then the <Child2> will be given the preference and vice-versa.  The following is a demonstration to support this statement.

// src/App.js  
  
import React from "react";  
import "./App.css";  
import { Helmet } from "react-helmet";  
import Child1 from "./Child1"; 
import Child2 from "./Child2";
   
function App() {  
  return (  
    <div className="App">  
  
      <Helmet>  
        <html lang="en" />  
        <title>React Helmet</title>  
        <meta name="description" content="Concept of React Helmet" />  
        <meta name="theme-color" content="#E6E6FA" />  
      </Helmet>  
  
      <header className="App-header">
      Title will not be React Helmet
      <Child1 />
      <Child2 />
      </header>  
    </div>  
  );  
}  
export default App; 

The title will be set according to the <Child2> component, as seen in the above code. If the sequence is reversed, the preference will be applied to <Child1>. This may be demonstrate using the code snippet below.

<header className="App-header">
      Title will not be React Helmet
      <Child2 />
      <Child1 />
</header> 

React Helmet with SSR integration

As previously said, React Helmet is often regarded as the best partner for app rendering on the server-side of the application; you can quickly reference the terminology by creating an example React SSR application. As a result, we must use the render static function in the Helmet in the application’s server-side code, exactly after the ReactDOMServerr’s renderToString or renderToStaticMarkup. Consider the code sample below to see how it’s done. /server/index.js

// server/index.js  
import React from "react";  
import { renderToString } from "react-dom/server";  
import express from "express";  
import App from "./src/App";  
import { Helmet } from "react-helmet";  
const app = express();    
  
app.get("/*", (req, res) => {  
  const app = renderToString(<App />);  
  const helmet = Helmet.renderStatic();  
  
  const html = `  
  <!DOCTYPE html>  
  <html ${helmet.htmlAttributes.toString()}>  
    <head>  
      ${helmet.title.toString()}  
      ${helmet.meta.toString()}  
      ${helmet.link.toString()}  
    </head>  
    <body ${helmet.bodyAttributes.toString()}>  
      <div id="root">  
        ${app}  
      </div>  
      </body>  
  </html>  
`;  
    res.send(html);  
});  
app.listen(8000);  

It’s important to note that every Helmet property has a function toString(). The HTML string is where this approach is most commonly utilize. It’s also an instance of Helmet’s render static, which returns with all of the attributes covered, such as the script, link, title, and so on, and all of these properties have the default function toString().

Working synchronously to complete the React Helmet’s SSR implementation isn’t always the best solution. The React Helmet would expose us to various dangers and failures if we were open or bound to make asynchronous queries like streaming. As a result, we employ the react-helmet-async approach to deal with this problem. This solution overcomes the problem by explicitly forking React Helmet. In the node environment, perform the following terminal command to install it.

npm i react-helmet-async  

After this command, we must ensure that everything except. HelmetProvider is kept so that the React tree is contained on both the server and client sides. The following is a simple illustration of how to do this. /src/App.js

// src/App.js  
  
import React from "react";  
import "./App.css";  
import { Helmet, HelmetProvider} from "react-helmet-async";  

function App() {  
  return (  
    <HelmetProvider>  
    <div className="App">  
      <Helmet>  
        <html lang="en" />  
        <title>React Helmet</title>  
        <meta name="description" content="Concept of React Helmet" />  
        <meta name="theme-color" content="#E6E6FA" />  
      </Helmet>  
      <header className="App-header">
      Title will be React Helmet
      </header>  
    </div>  
    </HelmetProvider>  
  );  
}  
export default App; 

React Helmet and React Router

If the application being built utilizes React Router for routing, React Helmet is an excellent option. One of the hooks associated with it is that we need to utilize React Helmet with every Router to keep the routes intact, as shown in the code snippet below. /src/App.js

// src/App.js  
import React from "react";  
import { Helmet } from "react-helmet";  
import { BrowserRouter, Switch, Route, Link } from "react-router-dom";  
import Home from './Home'  
import About from './About'  
export default function App() {  
  return (  
    <div>  
      <BrowserRouter>  
        <Switch>  
          <Route exact path="/">  
            <Home />  
          </Route>  
          <Route path="/about">  
            <About />  
          </Route>  
        </Switch>  
      </BrowserRouter>  
    </div>  
  );  
}  

/src/Home.js

// src/Home.js  
import React from "react";  
import { Helmet } from "react-helmet";  
import {  Link } from "react-router-dom";  
  
const Home = () => (  
  <div>  
    <Helmet>  
      <title>Home</title>  
    </Helmet>  
    <h2>Home.</h2>  
    <Link to="/about">About</Link>  
  </div>  
);  
  
export default Home 

/src/About.js

// src/About.js  
import React from "react";  
import { Helmet } from "react-helmet";  
import {  Link } from "react-router-dom";  
  
const About = () => (  
  <div>  
    <Helmet>  
      <title>About</title>  
    </Helmet>  
    <h2>About.</h2>  
    <Link to="/">Home</Link>  
  </div>  
);  
export default About; 

This is how React Helmet and React Router is use to route, and the approach may be applies to as many routes as possible.

Conclusion

We covered how to install, set up, and use React Helmet in this tutorial. React Helmet is a strong package that primarily serves as a document head manager, ensuring that our SEO is at the top of the page. It’s compact and easy to use, and it outlasts any library in its class provide the app is develop with the goal of staying at the top of the charts.

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn.

If you want to learn more about the ReactJS programming language then click the link to see our last article ReactJS Axios Delete Request with Code Example

Leave a Comment