Reputation: 57
In Reactjs, How to change the page title as dynamically. For Example: When we redirect to a new page that new page route line should come as a page title
For Example: If Home page then tile should be xxx Home, if in contact page then title should be xxx Contact
Upvotes: 1
Views: 1474
Reputation: 822
You can use Hooks, and on changing state you can use its useEffect()
method.
For example,
import React, { useState, useEffect } from 'react';
const Example = () => {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Picked from React Hooks documentation
Upvotes: 4
Reputation: 1223
Try this.
import React from 'react'
import ReactDOM from 'react-dom'
class TestPage extends React.Component{
componentDidMount(){
document.title = "Test page title"
}
render(){
return(
<p> hello world! </p>
);
}
}
ReactDOM.render(
<TestPage/>,
document.getElementById('root')
);
Upvotes: 0