Ad

Changing The Document Title In React?

- 1 answer

I'm trying to update the title of the document in a React app. I have very simple needs for this. The title is essentially used to put the Total component on display even when you're on a different tab.

This was my first instinct:

const React = require('react');

export default class Total extends React.Component {
  shouldComponentUpdate(nextProps) {
    //otherstuff
    document.title = this.props.total.toString();
    console.log("Document title: ", document.title);
    return true;
  }
  render() {
    document.title = this.props.total;
    return (
      <div className="text-center">
        <h1>{this.props.total}</h1>
      </div>
    );
  }
}

I thought this would just update the document.title every time this component was rendered, but it doesn't appear to do anything.

Not sure what I'm missing here. Probably something to do with how React runs this function - maybe somewhere that the document variable isn't available?

EDIT:

I'm starting a bounty for this question, as I still haven't found any solution. I've updated my code to a more recent version.

A weird development is that the console.logdoes print out the title I'm looking for. But for some reason, the actual title in the tab isn't updating. This issue is the same across Chrome, Safari, and Firefox.

Ad

Answer

I think webpack-dev-server runs in an iframe mode by default:

https://webpack.github.io/docs/webpack-dev-server.html#iframe-mode

So that might be why your attempts to set the title are failing. Try setting the inline option to true on webpack-dev-server, if you haven't already.

Ad
source: stackoverflow.com
Ad