Yash Choksi
Yash Choksi

Reputation: 513

How to change title of page when page is redirected using router in reactjs?

I have a mini project in which the first page having title homepage but the next page contacts is click through link it retains the homepage as title. I've explicitly declared title as Contact Us but then also it shows Homepage.

Here's my code:

For App.js:

import React, { Component } from 'react';
import {BrowserRouter as Router, Route, Switch, Link} from 'react-router-dom';
import ContactUs from '/Users/yashchoksi/Documents/linking/src/ContactUs';
class App extends Component {
  render() {
    return (
      <Router>
        <div>
          <title>HomePage</title>
          <Link to="/src/ContactUs">Contact Us</Link>
          <Switch>
            <Route exact path="/src/ContactUs" component={ContactUs}/>
          </Switch>
        </div>
      </Router>
    );
  }
}

export default App;

And for Contact Us page:

import React, { Component } from 'react';

class ContactUs extends Component {
  render(){
    return(
      <div>
        <title>ContactUs</title>
        Hello From COntactUs.
      </div>
    );
  }
}
export default ContactUs;

Please see and tell me how to declare title for dynamic naming!

Upvotes: 5

Views: 5603

Answers (3)

Amanshu Kataria
Amanshu Kataria

Reputation: 3346

Just use the following code:

componentWillMount(){
    document.title="Title name";
}

Edit:

componentWillMount will be deprecated in React 17, so you can use componentDidMount instead.

Upvotes: 5

medv
medv

Reputation: 141

For better api and server rendering, use react-helmet. It is also a one-liner at its simplest.

Upvotes: 0

Miguel Calder&#243;n
Miguel Calder&#243;n

Reputation: 3091

You can set it in your component:

import React, { Component } from 'react';

class ContactUs extends Component {
  componentDidMount() {
    document.title = 'Contact Us'
  }
  render(){
    return(
      <div>
        <title>ContactUs</title>
        Hello From COntactUs.
      </div>
    );
  }
}
export default ContactUs;

Upvotes: 8

Related Questions