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.log
does 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.
To change your logo, go to the public folder and change the favicon. ico . If you follow these steps, your logo and title will get changed. If it helps you, please mark as accepted answer.
To change Text component value dynamically with React Native, we can use a state. to define the myText state with useState with initial value set to 'Original Text' . Then we call setMyText to change the text value when we press the Text component.
I now use react-helmet for this purpose, as it allows to customize different meta tags and links, and it also supports SSR.
import { Helmet } from 'react-helmet' const Total = () => ( <div className="text-center"> <Helmet> <meta charSet="utf-8" /> <title>{this.props.total}</title> </Helmet> <h1>{this.props.total}</h1> </div> )
Original answer: there's actually a package by gaeron for this purpose, but in a declarative way:
import React, { Component } from 'react' import DocumentTitle from 'react-document-title' export default class Total extends Component { render () { return ( <DocumentTitle title={this.props.total}> <div className='text-center'> <h1>{this.props.total}</h1> </div> </DocumentTitle> ) } }
Inside your componentDidMount()
function in App.js
(or wherever), simply have:
componentDidMount() { document.title = "Amazing Page"; }
The reason this works is anywhere in your react project you have access to the Js global scope. Go ahead and type window
in your sites console. Basically everything there you will be able to access in your React project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With