I would like to set the document title (in the browser title bar) for my React application. I have tried using react-document-title (seems out of date) and setting document.title
in the constructor
and componentDidMount()
- none of these solutions work.
Changing the title tag You may edit the <title> tag in it to change the title from “React App” to anything else. Note that normally you wouldn't edit files in the public folder very often. For example, adding a stylesheet is done without touching the HTML.
Provides a declarative way to specify document. title in a single-page app. This component can be used on server side as well. Built with React Side Effect.
import React from 'react'
import ReactDOM from 'react-dom'
class Doc extends React.Component{
componentDidMount(){
document.title = "dfsdfsdfsd"
}
render(){
return(
<b> test </b>
)
}
}
ReactDOM.render(
<Doc />,
document.getElementById('container')
);
This works for me.
Edit: If you're using webpack-dev-server set inline to true
For React 16.8+ you can use the Effect Hook in function components:
import React, { useEffect } from 'react';
function Example() {
useEffect(() => {
document.title = 'My Page Title';
});
}
To manage all valid head tags, including <title>
, in declarative way, you can use React Helmet component:
import React from 'react'
import { Helmet } from 'react-helmet'
const TITLE = 'My Page Title'
class MyComponent extends React.PureComponent {
render () {
return (
<>
<Helmet>
<title>{ TITLE }</title>
</Helmet>
...
</>
)
}
}
For React 16.8, you can do this with a functional component using useEffect.
For Example:
useEffect(() => {
document.title = "new title"
}, []);
Having the second argument as an array calls useEffect only once, making it similar to componentDidMount
.
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