How to Dynamically set Title in React

May 06, 2017

Here’s a little snippet on how to do it.

// https://github.com/gigobyte/react-document-title-decorator/blob/master/example/setTitle.jsx
import React from 'react';

const setTitle = getTitle => WrappedComponent => {
  return class extends React.Component {
    updateTitle = props => {
      const title = getTitle(props);
      if (title) {
        document.title = title;
      }
    };

    componentDidMount() {
      this.updateTitle(this.props);
    }

    componentWillReceiveProps(props) {
      this.updateTitle(props);
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  };
};

export default setTitle;

👋 I'm Ashik Nesin • Sr. Frontend Engineer @Chargebee 👨‍💻• I write about modern Javascript & building web apps

© 2021 Nesin Technologies LLP