Как изменить title 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...

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.

theUtherSide's user avatar

theUtherSide

3,2584 gold badges34 silver badges35 bronze badges

asked Sep 11, 2017 at 16:36

eli's user avatar

3

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>
        ...
      </>
    )
  }
}

PSEUDO's user avatar

PSEUDO

1033 silver badges13 bronze badges

answered Sep 12, 2017 at 12:26

quotesBro's user avatar

quotesBroquotesBro

5,5542 gold badges29 silver badges41 bronze badges

9

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

theUtherSide's user avatar

theUtherSide

3,2584 gold badges34 silver badges35 bronze badges

answered Sep 11, 2017 at 16:44

AlexVestin's user avatar

AlexVestinAlexVestin

2,5082 gold badges15 silver badges20 bronze badges

8

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.

answered May 30, 2019 at 21:41

Jordan Daniels's user avatar

Jordan DanielsJordan Daniels

4,5931 gold badge19 silver badges29 bronze badges

3

As others have mentioned, you can use document.title = 'My new title' and React Helmet to update the page title. Both of these solutions will still render the initial ‘React App’ title before scripts are loaded.

If you are using create-react-app the initial document title is set in the <title> tag /public/index.html file.

You can edit this directly or use a placeholder which will be filled from environmental variables:

/.env:

REACT_APP_SITE_TITLE='My Title!'
SOME_OTHER_VARS=...

If for some reason I wanted a different title in my development environment —

/.env.development:

REACT_APP_SITE_TITLE='**DEVELOPMENT** My TITLE! **DEVELOPMENT**'
SOME_OTHER_VARS=...

/public/index.html:

<!DOCTYPE html>
<html lang="en">
    <head>
         ...
         <title>%REACT_APP_SITE_TITLE%</title>
         ...
     </head>
     <body>
         ...
     </body>
</html>

This approach also means that I can read the site title environmental variable from my application using the global process.env object, which is nice:

console.log(process.env.REACT_APP_SITE_TITLE_URL);
// My Title!

See: Adding Custom Environment Variables

answered Feb 13, 2019 at 9:57

Gruffy's user avatar

GruffyGruffy

1,3931 gold badge13 silver badges18 bronze badges

4

Since React 16.8. you can build a custom hook to do so (similar to the solution of @Shortchange):

export function useTitle(title) {
  useEffect(() => {
    const prevTitle = document.title
    document.title = title
    return () => {
      document.title = prevTitle
    }
  })
}

this can be used in any react component, e.g.:

const MyComponent = () => {
  useTitle("New Title")
  return (
    <div>
     ...
    </div>
  )
}

It will update the title as soon as the component mounts and reverts it to the previous title when it unmounts.

answered Oct 14, 2020 at 11:18

Master Bruce's user avatar

5

import React from 'react';

function useTitle(title: string): void => {
  React.useEffect(() => {
    const prevTitle = document.title;
    document.title = title;

    return () => {
      document.title = prevTitle;
    };
  }, []);
}

function MyComponent(): JSX.Element => {
  useTitle('Title while MyComponent is mounted');

  return <div>My Component</div>;
}

This is a pretty straight forward solution, useTitle sets the document title and when the component unmounts it’s reset to whatever it was previously.

answered Sep 24, 2020 at 14:53

Shortchange's user avatar

ShortchangeShortchange

3213 silver badges4 bronze badges

1

If you are wondering, you can set it directly inside the render function:

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
    render() {
        document.title = 'wow'
        return <p>Hello</p>
    }
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
)

For function component:

function App() {
    document.title = 'wow'
    return <p>Hello</p>
}

But, this is a bad practice because it will block the rendering (React prioritize the rendering first).

The good practice:

Class component:

class App extends React.Component {
    // you can also use componentDidUpdate() if the title is not static
    componentDidMount(){
        document.title = "good"
    }

    render() {
        return <p>Hello</p>
    }
}

Function component:

function App() {
    // for static title, pass an empty array as the second argument
    // for dynamic title, put the dynamic values inside the array
    // see: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
    useEffect(() => {
        document.title = 'good'
    }, []);

    return <p>Hello</p>
}

answered May 13, 2020 at 12:04

M Imam Pratama's user avatar

2

React Portals can let you render to elements outside the root React node (such at <title>), as if they were actual React nodes. So now you can set the title cleanly and without any additional dependencies:

Here’s an example:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Title extends Component {
    constructor(props) {
        super(props);
        this.titleEl = document.getElementsByTagName("title")[0];
    }

    render() {
        let fullTitle;
        if(this.props.pageTitle) {
            fullTitle = this.props.pageTitle + " - " + this.props.siteTitle;
        } else {
            fullTitle = this.props.siteTitle;
        }

        return ReactDOM.createPortal(
            fullTitle || "",
            this.titleEl
        );
    }
}
Title.defaultProps = {
    pageTitle: null,
    siteTitle: "Your Site Name Here",
};

export default Title;

Just put the component in the page and set pageTitle:

<Title pageTitle="Dashboard" />
<Title pageTitle={item.name} />

answered Feb 27, 2019 at 17:55

Colonel Thirty Two's user avatar

3

you should set document title in the life cycle of ‘componentWillMount’:

componentWillMount() {
    document.title = 'your title name'
  },

update for hooks:

useEffect(() => {
    document.title = 'current Page Title';
  }, []);

answered Sep 12, 2017 at 2:44

Alvin's user avatar

AlvinAlvin

2682 silver badges14 bronze badges

2

Helmet is really a great way of doing it, but for apps that only need to change the title, this is what I use:
(modern way React solution — using Hooks)

  1. Create change page title component
import React, { useEffect } from "react";

const ChangePageTitle = ({ pageTitle }) => {
  useEffect(() => {
    const prevTitle = document.title;
    document.title = pageTitle;
    return () => {
      document.title = prevTitle;
    };
  });

  return <></>;
};

export default ChangePageTitle;
  1. Use the component
import ChangePageTitle from "../{yourLocation}/ChangePageTitle";

...

return (
    <>
      <ChangePageTitle pageTitle="theTitleYouWant" />
      ...
    </>
  );

...

answered Sep 7, 2021 at 9:21

Aleksandar Hristov's user avatar

You have multiple options for this problem I would highly recommend to either use React Helmet or create a hook using useEffect. Instead of writing your own hook, you could also use the one from react-use:

React Helmet

import React from 'react';
import { Helmet } from 'react-helmet';

const MyComponent => () => (
  <Helmet>
    <title>My Title</title>
  </Helmet>
)

react-use

import React from 'react';
import { useTitle } from 'react-use';

const MyComponent = () => {
  useTitle('My Title');

  return null;
}

answered Mar 30, 2021 at 8:55

marcobiedermann's user avatar

marcobiedermannmarcobiedermann

3,8363 gold badges23 silver badges35 bronze badges

For React v18+, custom hooks will be the simplest approach.

Step 1: Create a hook. (hooks/useDocumentTitle.js)

import { useEffect } from "react";
export const useDocumentTitle = (title) => {

    useEffect(() => {
        document.title = `${title} - WebsiteName`;
    }, [title]);

    return null;
}

Step 2: Call the hook on every page with a custom title according to that page. (pages/HomePage.js)

import { useDocumentTitle } from "../hooks/useDocumentTitle";

const HomePage = () => {
    useDocumentTitle("Website Title For Home Page");
    
    return (
        <>           
            <main>
                <section>Example Text</section>
            </main>            
        </>
    );
}

export { HomePage };

Works well for dynamic pages as well, just pass the product title or whatever content you want to display.

answered Aug 9, 2022 at 11:17

Shubham Sarda's user avatar

Simply you can create a function in a js file and export it for usages in components

like below:

export default function setTitle(title) {
  if (typeof title !== "string") {
     throw new Error("Title should be an string");
  }
  document.title = title;
}

and use it in any component like this:

import React, { Component } from 'react';
import setTitle from './setTitle.js' // no need to js extension at the end

class App extends Component {
  componentDidMount() {
    setTitle("i am a new title");
  }

  render() {
    return (
      <div>
        see the title
      </div>
    );
  }
}

export default App

Emile Bergeron's user avatar

answered Apr 9, 2019 at 12:15

amin msh's user avatar

amin mshamin msh

4725 silver badges14 bronze badges

You can use the following below with document.title = 'Home Page'

import React from 'react'
import { Component } from 'react-dom'


class App extends Component{
  componentDidMount(){
    document.title = "Home Page"
  }

  render(){
    return(
      <p> Title is now equal to Home Page </p>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

or You can use this npm package npm i react-document-title

import React from 'react'
import { Component } from 'react-dom'
import DocumentTitle from 'react-document-title';


class App extends Component{


  render(){
    return(
      <DocumentTitle title='Home'>
        <h1>Home, sweet home.</h1>
      </DocumentTitle>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Happy Coding!!!

answered Aug 28, 2018 at 3:41

accimeesterlin's user avatar

accimeesterlinaccimeesterlin

4,3282 gold badges25 silver badges18 bronze badges

I haven’t tested this too thoroughly, but this seems to work. Written in TypeScript.

interface Props {
    children: string|number|Array<string|number>,
}

export default class DocumentTitle extends React.Component<Props> {

    private oldTitle: string = document.title;

    componentWillUnmount(): void {
        document.title = this.oldTitle;
    }

    render() {
        document.title = Array.isArray(this.props.children) ? this.props.children.join('') : this.props.children;
        return null;
    }
}

Usage:

export default class App extends React.Component<Props, State> {

    render() {
        return <>
            <DocumentTitle>{this.state.files.length} Gallery</DocumentTitle>
            <Container>
                Lorem ipsum
            </Container>
        </>
    }
}

Not sure why others are keen on putting their entire app inside their <Title> component, that seems weird to me.

By updating the document.title inside render() it’ll refresh/stay up to date if you want a dynamic title. It should revert the title when unmounted too. Portals are cute, but seem unnecessary; we don’t really need to manipulate any DOM nodes here.

answered Mar 29, 2019 at 8:10

mpen's user avatar

mpenmpen

266k263 gold badges831 silver badges1210 bronze badges

You can use ReactDOM and altering <title> tag

ReactDOM.render(
   "New Title",
   document.getElementsByTagName("title")[0]
);

answered Mar 3, 2020 at 11:42

reza moradi's user avatar

1

the easiest way is to use react-document-configuration

npm install react-document-configuration --save

Example:

import React from "react";
import Head from "react-document-configuration";

export default function Application() {
    return (
        <div>
            <Head title="HOME" icon="link_of_icon" />
            <div>
                <h4>Hello Developers!</h4>
            </div>
        </div>
    );
};```

Skully's user avatar

Skully

2,2343 gold badges22 silver badges31 bronze badges

answered Jan 30, 2021 at 22:55

you can create TabTittleHelper.js and

export const TabTittle = (newTitle) => {
document.title=newTitle;
return document.title;
};

later you writed all screens

TabTittle('tittleName');

answered Oct 7, 2022 at 6:25

BCHA's user avatar

I am not sure if it is a good practice or not, but In index.js headers I put:

document.title="Page Title";

answered Jan 12 at 21:45

Isabella's user avatar

const [name, setName] = useState("Jan");
  useEffect(() => 
    {document.title =   "Celebrate " +  {name}.name  ;}
  );
  

answered May 27, 2021 at 17:47

Sai Garuda's user avatar

2

I wanted to use page title to my FAQ page. So I used react-helmet for this.

First i installed react-helmet using npm i react-helmet

Then i added tag inside my return like this:

import React from 'react'
import { Helmet } from 'react-helmet'
const PAGE_TITLE = 'FAQ page'
export default class FAQ extends Component {
render () {
return (
{ PAGE_TITLE } This is my faq page ) } }

answered Jul 7, 2021 at 7:35

ANOOP NAYAK's user avatar

ANOOP NAYAKANOOP NAYAK

2953 silver badges7 bronze badges

If you’re a beginner you can just save yourself from all that by going to the public folder of your react project folder and edit the title in «index.html» and put yours. Don’t forget to save so it will reflect.

answered Aug 14, 2019 at 10:51

Stanflows's user avatar

The title is an essential element is any webpage that represents the document’s content globally. It maximizes the user experience for those who visit the website. Beyond that, the document title is used in many cases such as the title bar of the browser, bookmarks, stored history, navigation tabs of the browsers, session history, task bar, etc. Most importantly, they provide proper SEO content for the search engines. Having a proper title help boost the organic visitors towards the site improving the overall SEO performance as well.

In this tutorial, we will learn how to set a document title from react class components and hooks. React is one of the most popular library devised for creating powerful web apps. Here, we will learn how to add the document title in three different ways. We will start by simple one and end with a complex one.

So, let’s get started!

1. Add document title in a class components

In a class component, we can add the document title by using the componentDidMount()  lifecycle hook method. This lifecycle hook method executes right after the component is mounted to the DOM. By simply assessing the title property from document instance, we can add the title of the page as shown in the code snippet below:


  componentDidMount() {
    document.title = "About Page"; 
 }

  render() {
    return (
      <div className="App">
        <h1>Hello React App</h1>
      </div>
    );
  }
}

2. Using React Hooks

As of the latest versions of React, Hooks are becoming more popular as they optimize the overall workflow of the React ecosystem. Here, we can set the document title by using the useEffect hook. This hook executes at the initial stage when the component is mounted and also when the components state changes or the component re-renders. Inside the useEffect hook, we can simply set the document title as shown in the code snippet below:

import React, { useEffect} from "react";

export default function App() {

   useEffect(() => {
     document.title = "About Page";  
   }, []);

   return (
     <div className="App">
       <h1>Hello React App</h1>
     </div>
   );
}

3. Creating a Custom hook

This is an advanced form of setting the document title. This is not required in many cases but does help when the overall project is complex. Here, we simply formulate a custom hook that takes in a title as a prop and set it to the document inside the useEffect hook. Here, we assign the check variable to useEffect. Thus, the useEffect is triggered only when the check variable changes.

The implementation of the custom hook in the setDocumentTitle.js file is provided in the code snippet below:

import React, { useEffect, useState } from "react";

const useDocumentTitle = title => {
  const [document_title, setDoucmentTitle] = useState(title);
   useEffect(() => {
    document.title = document_title; 
  },[document_title]);

  return [document_title, setDoucmentTitle];
};

export {useDocumentTitle};

Now in order to use it, we need to import the useDocumentTitle hook from the setDocumentTitle file first in App.js. Then, we can simply pass the title name as a parameter in the useDocumentTitle hook as shown in the code snippet below:

import React from "react";
import {useDocumentTitle} from "setDocumentTitle"

export default function App() {
  const [document_title, setDoucmentTitle] = useDocumentTitle("Home page");
return (
    <div className="App">
      <h1>Hello React App</h1>
      <button onClick={() => setDoucmentTitle("About page")}>  
       Change document title     
       </button>   
     </div>
  );
}

Conclusion

The main goal of this tutorial was to showcase three different ways to set the document title in React ecosystem. It can be done in a simple as well as the complex way. The complex one simplifies the process in case the React project is a large one. In case of simpler project, simple way will work nicely. Also, we can the use of lifecycle hook for class component and use of React hooks for the functional component.

🤩 Our Amazing Sponsors 👇

This article shows you 2 approaches to programmatically changing the page title in a React web app. We will go through 2 examples: the first one uses self-written code, and the second one makes use of a third-party library called React Helmet.

Using self-written code

Example Preview

In this example, our app is initially titled “Default Title”. However, the page title can change whenever the user enters (or remove) something in the text field.

The Complete Code

// App.js
// Kindacode.com
import { useEffect, useState } from "react";

const App = () => {
  const [title, setTitle] = useState("Default Title");

  useEffect(() => {
    // This will run when the page first loads and whenever the title changes
    document.title = title;
  }, [title]);

  const changeTitle = (event) => {
    setTitle(event.target.value);
  };

  return (
    <div style={styles.container}>
      <input
        type="text"
        onChange={changeTitle}
        value={title}
        style={styles.input}
      />
    </div>
  );
};

export default App;

// Just some styles
const styles = {
  container: {
    width: 500,
    margin: "50px auto",
    display: "flex",
    justifyContent: "center",
  },
  input: {
    width: 300,
    padding: "5px 20px",
  },
};

Using the React Helmet Async package

React Helmet Async is a popular open-source React library that manages all of your changes to the document head. You can add it to your project by running:

npm i react-helmet-async

React Helmet Async is a fork of React Helmet.

Example Preview

In this example, we pretend to be fetching data from a server and it takes 3 seconds to be done. When the data fetching is complete, the page title will be updated.

The Full Code

// App.js
// Kindacode.com
import { useEffect, useState } from "react";

import { Helmet, HelmetProvider } from "react-helmet-async";

const App = () => {
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("Loading...");

  useEffect(() => {
    const fetchData = async () => {
      // We pretend to be fetching data from a server and it takes 3 seconds
      await new Promise((resolve) => setTimeout(resolve, 3000));

      // When the data "fetching" process is complete, we will set the title and content
      setTitle("This is a cool title");
      setContent("Everything is done");
    };

    fetchData();
  }, []);

  return (
    <HelmetProvider>
      <Helmet>
        <title>{title ? title : "No title"}</title>
      </Helmet>

      <div style={{ padding: 100 }}>
        <h1>{content}</h1>
      </div>
    </HelmetProvider>
  );
};

export default App;

Conclusion

In the vast majority of modern web applications (especially single-page applications), the content is loaded dynamically from the server instead of static text like in the 90s. That’s why we need to set the page titles programmatically, as in the 2 examples above.

If you would like to explore more about React and frontend development, take a look at the following articles:

  • React + TypeScript: Handling onFocus and onBlur events
  • React: Create an Animated Side Navigation from Scratch
  • React: Copy to Clipboard When Click a Button/Link
  • 5 best open-source WYSIWYG editors for React
  • How to create a Filter/Search List in React
  • React: How to Create a Responsive Navbar from Scratch

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

This article describes two ways to change the document title in React Js.

  1. Using pure Javascript document.title
  2. Using NPM package React-Helmet

Using pure Javascript document.title

Here I use pure Javascript to set the page title.

import { useEffect } from "react"
export const SignupForm = () =>{
useEffect(() => {
  document.title = "LearnBestCoding Page title"
})
 return(
  <>
    <p>Some page content</p>
  </>
 )
}
React Js set page title
Figure 1: React Js set page title

But be aware that you cannot see these details if you view the page source because this is React Js.

Using NPM package React-Helmet

If you prefer not to use the above method for some reason, an NPM package is built just for this.

Install the NPM package by running:

or, if you use Typescript, use:

npm i --save-dev @types/react-helmet
import {Helmet} from "react-helmet";
export const SignupForm = () =>{
 return(
    < Helmet>
          <meta charSet="utf-8" />
          <title>LearnBestCoding Page title</title>
          <link rel="canonical" href="http://www.learnbestcoding.com" />
     </Helmet>
 )
}

Advantages of using react-helmet

React Helmet needs an additional NPM package. However, it has some advantages over the Javascript approach.

React Helmet allows me to nest header information. Meaning my child component’s Helmet overrides my parent component’s Helmet contents.

import { Helmet } from "react-helmet"
import { SignupForm } from "./components/Child"
export default const Parent = () => {
  return(
    <>
     <Helmet>
          <meta charSet="utf-8" />
          <title>Parent Page Title</title>
          <link rel="canonical" href="http://www.learnbestcoding.com" />
     </Helmet>
      <Child />
    </>
  )
}
import {Helmet} from "react-helmet";
export const Child = () =>{
 return(
    <Helmet>
          <meta charSet="utf-8" />
          <title>Child Page Title</title>
          <link rel="canonical" href="http://www.learnbestcoding.com" />
     </Helmet>
 )
}

In the above example, the Child component’s Helmet content overrides the parent’s Helmet details.

I wrote react-document-title just for that.

It provides a declarative way to specify document.title in a single-page app.
If you want to get title on server after rendering components to string, call DocumentTitle.rewind().

Features

  • Does not emit DOM, not even a <noscript>;
  • Like a normal React compoment, can use its parent’s props and state;
  • Can be defined in many places throughout the application;
  • Supports arbitrary levels of nesting, so you can define app-wide and page-specific titles;
  • Works on client and server.

Example

Assuming you use something like react-router:

var App = React.createClass({
  render: function () {
    // Use "My Web App" if no child overrides this
    return (
      <DocumentTitle title='My Web App'>
        <this.props.activeRouteHandler />
      </DocumentTitle>
    );
  }
});

var HomePage = React.createClass({
  render: function () {
    // Use "Home" while this component is mounted
    return (
      <DocumentTitle title='Home'>
        <h1>Home, sweet home.</h1>
      </DocumentTitle>
    );
  }
});

var NewArticlePage = React.createClass({
  mixins: [LinkStateMixin],

  render: function () {
    // Update using value from state while this component is mounted
    return (
      <DocumentTitle title={this.state.title || 'Untitled'}>
        <div>
          <h1>New Article</h1>
          <input valueLink={this.linkState('title')} />
        </div>
      </DocumentTitle>
    );
  }
});

Source

I keep track of mounted instances and only use title given to the top DocumentTitle in the mounted instance stack whenever it updates, gets mounted or unmounted. On server, componentWillMount fires but we won’t get didMount or willUnmount, so we introduce DocumentTitle.rewind() that returns a string and destroys state to prepare for next request.

var DocumentTitle = React.createClass({
  propTypes: {
    title: PropTypes.string
  },

  statics: {
    mountedInstances: [],

    rewind: function () {
      var activeInstance = DocumentTitle.getActiveInstance();
      DocumentTitle.mountedInstances.splice(0);

      if (activeInstance) {
        return activeInstance.props.title;
      }
    },

    getActiveInstance: function () {
      var length = DocumentTitle.mountedInstances.length;
      if (length > 0) {
        return DocumentTitle.mountedInstances[length - 1];
      }
    },

    updateDocumentTitle: function () {
      if (typeof document === 'undefined') {
        return;
      }

      var activeInstance = DocumentTitle.getActiveInstance();
      if (activeInstance) {
        document.title = activeInstance.props.title;
      }
    }
  },

  getDefaultProps: function () {
    return {
      title: ''
    };
  },

  isActive: function () {
    return this === DocumentTitle.getActiveInstance();
  },

  componentWillMount: function () {
    DocumentTitle.mountedInstances.push(this);
    DocumentTitle.updateDocumentTitle();
  },

  componentDidUpdate: function (prevProps) {
    if (this.isActive() && prevProps.title !== this.props.title) {
      DocumentTitle.updateDocumentTitle();
    }
  },

  componentWillUnmount: function () {
    var index = DocumentTitle.mountedInstances.indexOf(this);
    DocumentTitle.mountedInstances.splice(index, 1);
    DocumentTitle.updateDocumentTitle();
  },

  render: function () {
    if (this.props.children) {
      return Children.only(this.props.children);
    } else {
      return null;
    }
  }
});

module.exports = DocumentTitle;

I wrote react-document-title just for that.

It provides a declarative way to specify document.title in a single-page app.
If you want to get title on server after rendering components to string, call DocumentTitle.rewind().

Features

  • Does not emit DOM, not even a <noscript>;
  • Like a normal React compoment, can use its parent’s props and state;
  • Can be defined in many places throughout the application;
  • Supports arbitrary levels of nesting, so you can define app-wide and page-specific titles;
  • Works on client and server.

Example

Assuming you use something like react-router:

var App = React.createClass({
  render: function () {
    // Use "My Web App" if no child overrides this
    return (
      <DocumentTitle title='My Web App'>
        <this.props.activeRouteHandler />
      </DocumentTitle>
    );
  }
});

var HomePage = React.createClass({
  render: function () {
    // Use "Home" while this component is mounted
    return (
      <DocumentTitle title='Home'>
        <h1>Home, sweet home.</h1>
      </DocumentTitle>
    );
  }
});

var NewArticlePage = React.createClass({
  mixins: [LinkStateMixin],

  render: function () {
    // Update using value from state while this component is mounted
    return (
      <DocumentTitle title={this.state.title || 'Untitled'}>
        <div>
          <h1>New Article</h1>
          <input valueLink={this.linkState('title')} />
        </div>
      </DocumentTitle>
    );
  }
});

Source

I keep track of mounted instances and only use title given to the top DocumentTitle in the mounted instance stack whenever it updates, gets mounted or unmounted. On server, componentWillMount fires but we won’t get didMount or willUnmount, so we introduce DocumentTitle.rewind() that returns a string and destroys state to prepare for next request.

var DocumentTitle = React.createClass({
  propTypes: {
    title: PropTypes.string
  },

  statics: {
    mountedInstances: [],

    rewind: function () {
      var activeInstance = DocumentTitle.getActiveInstance();
      DocumentTitle.mountedInstances.splice(0);

      if (activeInstance) {
        return activeInstance.props.title;
      }
    },

    getActiveInstance: function () {
      var length = DocumentTitle.mountedInstances.length;
      if (length > 0) {
        return DocumentTitle.mountedInstances[length - 1];
      }
    },

    updateDocumentTitle: function () {
      if (typeof document === 'undefined') {
        return;
      }

      var activeInstance = DocumentTitle.getActiveInstance();
      if (activeInstance) {
        document.title = activeInstance.props.title;
      }
    }
  },

  getDefaultProps: function () {
    return {
      title: ''
    };
  },

  isActive: function () {
    return this === DocumentTitle.getActiveInstance();
  },

  componentWillMount: function () {
    DocumentTitle.mountedInstances.push(this);
    DocumentTitle.updateDocumentTitle();
  },

  componentDidUpdate: function (prevProps) {
    if (this.isActive() && prevProps.title !== this.props.title) {
      DocumentTitle.updateDocumentTitle();
    }
  },

  componentWillUnmount: function () {
    var index = DocumentTitle.mountedInstances.indexOf(this);
    DocumentTitle.mountedInstances.splice(index, 1);
    DocumentTitle.updateDocumentTitle();
  },

  render: function () {
    if (this.props.children) {
      return Children.only(this.props.children);
    } else {
      return null;
    }
  }
});

module.exports = DocumentTitle;

Change the page title when the user routes to a new page.

There are many ways to get the page title to change and some great tools to assist you. There is a particularly great tool that will do that and a bit more. It’s called react-helmet.

It can set anything that occurs in the head of the document.

It has a great declarative API because it’s exposed as just another component.

Using react-helmet

To use this feat of software engineering, we’ll install it:

npm install react-helmet

And then use it inside of one or more of our components.

Let’s say that we have a home page and an about page. We might have a top-level component as the entry point for each page. We would put a call to react-helmet in each of these components, assigning the respective titles:

import { Helmet } from 'react-helmet'

const Home = _ => 
  
Muffins R Us

Welcome to muffin land. It's breakfast time!

const About = _ =>
About | Muffins R Us

How we got into muffins.

No when your router changes components from Home to About or vice versa, the Helmet will engage and change your site’s title.

Depending on your site design, you could change the site title even when the URL hasn’t changed. Since the title is set when a component is rendered, all you’d need to do is render a component with a different </Helmet></code> declaration inside it, and the site title would change.</p><p>How else do you handle updating the page title in a React app?</p><p>Or have you found other interesting uses for <code>react-helmet</code>?</p></div></article></main></body><footer class="spacer"><nav class="main-footer__nav"><ul class="reset"><li>© 2023 Jake Trent</li><li><a class="hover pink" href="/post">[Posts]</a></li><li><a class="hover pink" href="/tags">[Tags]</a></li><li><a class="hover pink" href="mailto:hi@jaketrent.com">[Contact]</a></li><li><a class="hover orange" href="/post/feed.xml">[Feed]</a></li><li><a class="hover pink" href="/sitemap.xml">[Sitemap]</a></li></ul></nav></footer></html>

Понравилась статья? Поделить с друзьями:
  • Как изменить sysctl
  • Как изменить title drupal
  • Как изменить swf игру
  • Как изменить title 1c bitrix
  • Как изменить swappiness