Categories
React Answers

How to Update Page Title in a React App?

Spread the love

Oftentimes, we want to update the title of a web page in our React app.

In this article, we’ll look at how to update the title of a web page in our React app.

Update Page Title in a React App

To make updating the title of a React app easy, we can use the react-document-title package to do it.

To install it, we run:

npm install --save react-document-title

Then we can use it by writing:

function App() {
  return (
    <DocumentTitle title='My App'>
      hello world
    </DocumentTitle>
  );
}

Then ‘My App’ will be the title of our React app.

When we switch components, we can switch the title of the document.

For instance, we can write:

function HomePage() {
  return (
    <DocumentTitle title='Home'>
      <h1>home page.</h1>
    </DocumentTitle>
  );
}

We just wrap our component with the DocumentTitle component to set the title.

It also works with class components:

class NewArticlePage extends React.Component {
  constructor(props) {
    super(props);
    this.state = { title: 'Untitled' };
  }

  render() {
    return (
      <DocumentTitle title={this.state.title}>
        <div>
          <input
            value={this.state.title}
            onChange={(e) => this.setState({ title: e.target.value         })}
          />
        </div>
      </DocumentTitle>
    );
  }
}

We can make the state dynamic by passing in the state variable into the title prop.

It also works with server-side rendered apps.

There’s also the react-helmet plugin which lets us set the page title and more.

To set the title with it, we use the Helmet component with the title element inside.

For instance, we can write:

import React from "react";
import {Helmet} from "react-helmet";

class App extends React.Component {
  render () {
    return (
      <div>
        <Helmet>
          <meta charSet="utf-8" />
          <title>My Title</title>
        </Helmet>
        {/* ... */}
      </div>
    );
  }
};

We can use it to add any element we can add in the head tag, including the title tag.

It also works with both client and server-side rendered apps.

Conclusion

To make updating the title of a React app easy, we can use the react-document-title package to do it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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