So, I've figured out how to create dynamic titles based on what page I'm on but whenever I go to build the project, I am getting told that 'location is undefined'.
Here's my function that I'm placing inside 'layouts/index.js' above TemplateWrapper
function page(props) {
// Split the pathname string into an array of sub-paths
let myLocation = location.pathname.split('/').join('');
if (myLocation === '') {
myLocation = 'Home';
} else if (myLocation === 'about-us') {
myLocation = 'About Us';
} else if (myLocation === 'services-training') {
myLocation = 'Services & Training';
} else if (myLocation === 'carriages-wagons') {
myLocation = 'Carriages & Wagons';
} else if (myLocation === 'contact-us') {
myLocation = 'Contact Us';
}
return myLocation
}
const TemplateWrapper = ({ location, children, data }) => (
<div>
<Helmet
title={` ${page()} - ${data.site.siteMetadata.title}` }
meta={[
{ name: 'description', content: 'Sample' },
{ name: 'keywords', content: 'sample, something' },
]}
/>
<Header siteTitle={data.site.siteMetadata.title} />
{children()}
<Footer />
</div>
)
The build should be successful as it doesn't seem to result in an error
'gatsby build' results in error with WebpackError: location is not defined
npm list gatsby): [email protected]gatsby --version): 1.1.50You should pass location to page function and better yet - just use <Helmet> component in your pages to overwrite title
Apologies, I'm still learning React.
When I pass 'location' to the page function:
function page(props, location) { ... }
I now get this on build: WebpackError: Cannot read property 'pathname' of undefined.
Do you mind providing an example of what the code may look like with your suggestion?
You need changes like this:
---function page(props) {
+++function page(location) {
-title={` ${page()} - ${data.site.siteMetadata.title}` }
+title={` ${page(location)} - ${data.site.siteMetadata.title}` }
Thank you, this worked!
Thanks I had the same problem, This is very useful for anyone trying to improve the SEO health of their Gatsby website!
Most helpful comment
You need changes like this: