Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 818
Yash Choksi Avatar asked Dec 13 '22 18:12

Yash Choksi


2 Answers

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;
like image 134
Miguel Calderón Avatar answered Dec 17 '22 23:12

Miguel Calderón


Just use the following code:

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

Edit:

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

like image 37
Amanshu Kataria Avatar answered Dec 17 '22 22:12

Amanshu Kataria