Reputation: 513
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
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
Reputation: 141
For better api and server rendering, use react-helmet. It is also a one-liner at its simplest.
Upvotes: 0
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