Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you set the document title in React?

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.

like image 738
eli Avatar asked Sep 11 '17 16:09

eli


People also ask

How do I change my title in Reactjs?

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.

What is document Title React?

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.


3 Answers

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

like image 94
AlexVestin Avatar answered Nov 03 '22 00:11

AlexVestin


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>
        ...
      </>
    )
  }
}
like image 22
quotesBro Avatar answered Nov 03 '22 02:11

quotesBro


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.

like image 42
Jordan Daniels Avatar answered Nov 03 '22 00:11

Jordan Daniels