Dynamic Page Title With ReactJS
I want to make a Dynamic page title on ReactJS. I try a lot of things , but didn't succeed. I make an array with data:
let pageTitles = [
{key:"/Home", title:"Welcome Home"},
{key:"/SecondPage", title:"Shop"},
{key:"/ThirdPage", title:"ContactUs"},
];
In html is only <title></title>
, I use let pathname = window.location.pathname;
If it return "/Home" or "/ThirdPage" to set a new title dynamically.
I've tried something like that:
for (var i = 0, len = pageTitles.length; i < len; i++) {
if (pageTitles[i].key === pathname) {
var hhh = pageTitles[i].text;
}
}
document.title = hhh
But obviously didn't work. I'm sorry if there is a topic like that, but I didn't found it.I have a restriction to install modules.
Answer
If you need to avoid installing modules, you could do this as helper file, then just import it in module you need and call in componentDidMount
export function seo(data = {}) {
data.title = data.title || 'Default title';
data.metaDescription = data.metaDescription || 'Default description';
document.title = data.title;
document.querySelector('meta[name="description"]').setAttribute('content', data.metaDescription);
}
import React from 'react';
import {seo} from '../helpers/seo';
export default class SomeClass extends Component {
constructor(props) {
super(props);
};
componentDidMount() {
seo({
title: 'This is my title only shown on this page',
metaDescription: 'With some meta description'
});
}
render() {
return <h1>Hello World</h1>;
}
}
You could also just call directly document.title = 'My new title'
anywhere, but if you extract it as function you have the option to have default one and just provide override when you want to.
Edit: upon inspecting your code, if you change hhh = pageTitles[i].text;
to hhh = pageTitles[i].title;
it will work. Would be nice to declare the var
outside of the loop. Also would be nice to have default value.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM