score:163
You can use React Helmet:
import React from 'react'
import { Helmet } from 'react-helmet'
const TITLE = 'My Page Title'
class MyComponent extends React.PureComponent {
render () {
return (
<>
<Helmet>
<title>{ TITLE }</title>
</Helmet>
...
</>
)
}
}
score:-9
If you're a beginner you can just save yourself from all that by going to the public folder of your react project folder and edit the title in "index.html" and put yours. Don't forget to save so it will reflect.
score:-1
const [name, setName] = useState("Jan");
useEffect(() =>
{document.title = "Celebrate " + {name}.name ;}
);
score:-1
I wanted to use page title to my FAQ page. So I used react-helmet for this.
First i installed react-helmet using npm i react-helmet
Then i added tag inside my return like this:
import React from 'react'
import { Helmet } from 'react-helmet'
const PAGE_TITLE = 'FAQ page'
export default class FAQ extends Component {
render () {
return (
{ PAGE_TITLE } This is my faq page ) } }
score:0
the easiest way is to use react-document-configuration
npm install react-document-configuration --save
Example:
import React from "react";
import Head from "react-document-configuration";
export default function Application() {
return (
<div>
<Head title="HOME" icon="link_of_icon" />
<div>
<h4>Hello Developers!</h4>
</div>
</div>
);
};```
score:1
You can use ReactDOM and altering <title>
tag
ReactDOM.render(
"New Title",
document.getElementsByTagName("title")[0]
);
score:2
I haven't tested this too thoroughly, but this seems to work. Written in TypeScript.
interface Props {
children: string|number|Array<string|number>,
}
export default class DocumentTitle extends React.Component<Props> {
private oldTitle: string = document.title;
componentWillUnmount(): void {
document.title = this.oldTitle;
}
render() {
document.title = Array.isArray(this.props.children) ? this.props.children.join('') : this.props.children;
return null;
}
}
Usage:
export default class App extends React.Component<Props, State> {
render() {
return <>
<DocumentTitle>{this.state.files.length} Gallery</DocumentTitle>
<Container>
Lorem ipsum
</Container>
</>
}
}
Not sure why others are keen on putting their entire app inside their <Title>
component, that seems weird to me.
By updating the document.title
inside render()
it'll refresh/stay up to date if you want a dynamic title. It should revert the title when unmounted too. Portals are cute, but seem unnecessary; we don't really need to manipulate any DOM nodes here.
score:6
You can use the following below with document.title = 'Home Page'
import React from 'react'
import { Component } from 'react-dom'
class App extends Component{
componentDidMount(){
document.title = "Home Page"
}
render(){
return(
<p> Title is now equal to Home Page </p>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
or You can use this npm package npm i react-document-title
import React from 'react'
import { Component } from 'react-dom'
import DocumentTitle from 'react-document-title';
class App extends Component{
render(){
return(
<DocumentTitle title='Home'>
<h1>Home, sweet home.</h1>
</DocumentTitle>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
Happy Coding!!!
score:6
Helmet is really a great way of doing it, but for apps that only need to change the title, this is what I use: (modern way React solution - using Hooks)
- Create change page title component
import React, { useEffect } from "react";
const ChangePageTitle = ({ pageTitle }) => {
useEffect(() => {
const prevTitle = document.title;
document.title = pageTitle;
return () => {
document.title = prevTitle;
};
});
return <></>;
};
export default ChangePageTitle;
- Use the component
import ChangePageTitle from "../{yourLocation}/ChangePageTitle";
...
return (
<>
<ChangePageTitle pageTitle="theTitleYouWant" />
...
</>
);
...
score:8
Simply you can create a function in a js file and export it for usages in components
like below:
export default function setTitle(title) {
if (typeof title !== "string") {
throw new Error("Title should be an string");
}
document.title = title;
}
and use it in any component like this:
import React, { Component } from 'react';
import setTitle from './setTitle.js' // no need to js extension at the end
class App extends Component {
componentDidMount() {
setTitle("i am a new title");
}
render() {
return (
<div>
see the title
</div>
);
}
}
export default App
score:8
You have multiple options for this problem I would highly recommend to either use React Helmet
or create a hook using useEffect
. Instead of writing your own hook, you could also use the one from react-use
:
React Helmet
import React from 'react';
import { Helmet } from 'react-helmet';
const MyComponent => () => (
<Helmet>
<title>My Title</title>
</Helmet>
)
react-use
import React from 'react';
import { useTitle } from 'react-use';
const MyComponent = () => {
useTitle('My Title');
return null;
}
score:12
you should set document title in the life cycle of 'componentWillMount':
componentWillMount() {
document.title = 'your title name'
},
score:14
If you are wondering, you can set it directly inside the render function:
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
render() {
document.title = 'wow'
return <p>Hello</p>
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
)
For function component:
function App() {
document.title = 'wow'
return <p>Hello</p>
}
But, this is a bad practice because it will block the rendering (React prioritize the rendering first).
The good practice:
Class component:
class App extends React.Component {
// you can also use componentDidUpdate() if the title is not static
componentDidMount(){
document.title = "good"
}
render() {
return <p>Hello</p>
}
}
Function component:
function App() {
// for static title, pass an empty array as the second argument
// for dynamic title, put the dynamic values inside the array
// see: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
useEffect(() => {
document.title = 'good'
}, []);
return <p>Hello</p>
}
score:15
React Portals can let you render to elements outside the root React node (such at <title>
), as if they were actual React nodes. So now you can set the title cleanly and without any additional dependencies:
Here's an example:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Title extends Component {
constructor(props) {
super(props);
this.titleEl = document.getElementsByTagName("title")[0];
}
render() {
let fullTitle;
if(this.props.pageTitle) {
fullTitle = this.props.pageTitle + " - " + this.props.siteTitle;
} else {
fullTitle = this.props.siteTitle;
}
return ReactDOM.createPortal(
fullTitle || "",
this.titleEl
);
}
}
Title.defaultProps = {
pageTitle: null,
siteTitle: "Your Site Name Here",
};
export default Title;
Just put the component in the page and set pageTitle
:
<Title pageTitle="Dashboard" />
<Title pageTitle={item.name} />
score:21
import React from 'react';
function useTitle(title: string): void => {
React.useEffect(() => {
const prevTitle = document.title;
document.title = title;
return () => {
document.title = prevTitle;
};
}, []);
}
function MyComponent(): JSX.Element => {
useTitle('Title while MyComponent is mounted');
return <div>My Component</div>;
}
This is a pretty straight forward solution, useTitle
sets the document title and when the component unmounts it's reset to whatever it was previously.
score:34
Since React 16.8. you can build a custom hook to do so (similar to the solution of @Shortchange):
export function useTitle(title) {
useEffect(() => {
const prevTitle = document.title
document.title = title
return () => {
document.title = prevTitle
}
})
}
this can be used in any react component, e.g.:
const MyComponent = () => {
useTitle("New Title")
return (
<div>
...
</div>
)
}
It will update the title as soon as the component mounts and reverts it to the previous title when it unmounts.
score:47
As others have mentioned, you can use document.title = 'My new title'
and React Helmet to update the page title. Both of these solutions will still render the initial 'React App' title before scripts are loaded.
If you are using create-react-app
the initial document title is set in the <title>
tag /public/index.html
file.
You can edit this directly or use a placeholder which will be filled from environmental variables:
/.env
:
REACT_APP_SITE_TITLE='My Title!'
SOME_OTHER_VARS=...
If for some reason I wanted a different title in my development environment -
/.env.development
:
REACT_APP_SITE_TITLE='**DEVELOPMENT** My TITLE! **DEVELOPMENT**'
SOME_OTHER_VARS=...
/public/index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
...
<title>%REACT_APP_SITE_TITLE%</title>
...
</head>
<body>
...
</body>
</html>
This approach also means that I can read the site title environmental variable from my application using the global process.env
object, which is nice:
console.log(process.env.REACT_APP_SITE_TITLE_URL);
// My Title!
score:137
For React 16.8, you can do this with a functional component using useEffect.
For Example:
useEffect(() => {
document.title = "new title"
}, []);
Having the second argument as an array calls useEffect only once, making it similar to componentDidMount
.
score:181
import React from 'react'
import ReactDOM from 'react-dom'
class Doc extends React.Component{
componentDidMount(){
document.title = "dfsdfsdfsd"
}
render(){
return(
<b> test </b>
)
}
}
ReactDOM.render(
<Doc />,
document.getElementById('container')
);
This works for me.
Edit: If you're using webpack-dev-server set inline to true
Source: stackoverflow.com
Related Query
- How do you set the document title in React?
- How do you set the Typescript type for useRef hook in React Native?
- How do I set up an internal link in react that navigates the current document
- How to set the DefaultRoute to another Route in React Router
- How do you inspect a react element's props & state in the console?
- How do you make the ListHeaderComponent of a React Native FlatList sticky?
- How to set the height of button in React Native Android
- React router v4 - How do you access the state that is passed via Redirect?
- How do you change the Stepper color on React Material UI?
- How to set the width of a React component during test?
- React: If you set state in a request animation frame will react schedule rendering on the animation frame?
- How do you update Formik initial values with the react context api values after an AJAX request?
- How to TEST async calls made in componentDidMount that set the state of React Component
- How Do you reset the CSS in React if you're doing styled components?
- How can you remove a Jquery Document Click Listeners Effecting React Element?
- How do you pass data when using the navigate function in react router v6
- How do you dynamically insert a React component into the DOM (for instance a dialog)?
- How can I set the content offset of a FlatList in React Native?
- How can I set the source of an image dynamically in React native?
- How can I programmatically set the user details for Launch Darkly in my react app
- How to setup sublime 3 with react native so that when you click on the error and it jump to your code?
- How do I set system preference dark mode in a react app but also allow users to toggle back and forth the current theme
- How can you use the 'this' keyword inside of a function signature to set a default parameter?
- How to dynamically change the title of a website in react js (also in source code)?
- Reading firestore sub-collection data in react - how to set a parent id in the sub-collection where query
- How do you set the material-ui cardholder avatar?
- React > How to set focus on the input field after adding a new row by using react-table
- page title not available with jest/enzyme for testing react app, how to get the title?
- How do you pass a prop to all react routes? (Change title dynamically)
- How to set the default react context value as data from firestore?
More Query from same tag
- how can we check if condition in reactjs
- Webpack & Bower: Multiple css & js files
- What are the valid symbols for a React 'key'
- ReactJS - Pass props with Redirect component
- Materializecss tabs are not working with React (npm import)
- Npm start problem while installing react, and how to fix it?
- Wrapping h5 in Link tag made h5 dissappear
- How to use react as a component library rather than application
- How to render HTML from a prop coming from MongoDB
- useRef TypeScript - not assignable to type LegacyRef<HTMLDivElement>
- Loading a name based on Value from Parent Component Dynamically
- How to execute OS paste action via electron
- Wildfly for backend and NGINX for frontend
- React project script linter error Missing "key" prop for element in iterator
- Dynamically appended JSX isn't transpiled by Babel Standalone when Babel is appended dynamically
- So how can I sum all the values in all objects in an array which is coming from react redux?
- How do I test component that uses react context API?
- How to bind an Object to select in reactjs?
- How to display a div element on a specific key in a map in react
- Splitting React components into separate files
- Toggling checkboxes in React
- Using Ant Design and Moment Js, I'm still unable to figure out how can we sort columns using Dates?
- Objects are not valid as a React child with React.memo
- Get string from mail body via regex?
- How to solve Unable to resolve type: React.ReactEnvironment Exception
- How to Build NextJS Project on Local without Now
- First steps in Redux. How to add value to mapStateToProps?
- Unexpected token PropTypes
- Background should take the entire space and
- How to set object value one by one in into text field using map function in reactjs