5

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!

3 Answers 3

8

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;
Sign up to request clarification or add additional context in comments.

4 Comments

And what if I have more than 2 pages? Can I do it in similar way??
Yes, you can ;)
@MiguelCalderón Do we have any approach for setting document title dynamically with client-side routing?
@VikasSingh Depends on the complexity of your routes. In general, I think you can follow Dan Abramov's advice: github.com/ReactTraining/react-router/issues/… That is, either use his react-document-title package (quite outdated now) or create your own DocumentTitle component. It shouldn´t be too difficult.
5

Just use the following code:

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

Edit:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.