question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to pass dynamic props (title,description,keywords,canonical) to _document.js for each page

See original GitHub issue

We have created custom _document.js page in page folder .So that we can easily add GTM(Google tag Manager) in body and head.

_document.js

import React from 'react'
import Document, { Head, Main, NextScript } from 'next/document'
import flush from 'styled-jsx/server'
import PropTypes from 'prop-types';
const defaultDescription = ''
const defaultOGURL = ''
const defaultOGImage = ''

export default class MyDocument extends Document {
  static getInitialProps ({ renderPage }) {
    const {html, head, errorHtml, chunks} = renderPage()
    const styles = flush()
    return { html, head, errorHtml, chunks, styles }
  }

  
  render () {
      
    return (
      <html>
        <Head>
          
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
          <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
          <title>{this.props.title || ''}</title>
          <meta name="description" content={this.props.description || defaultDescription} />
          <meta name="keywords" content={this.props.keywords || ''} />
          <meta name="robots" content="INDEX,FOLLOW" />
          <meta name="HandheldFriendly" content="true" />
          <link rel="canonical" href={this.props.canonical || ''} />
          <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css" />
          <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap-theme.min.css" />
          
          <link  href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" />
           
           <script dangerouslySetInnerHTML={{__html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
                new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
                j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
                'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
              })(window,document,'script','dataLayer','GTM-XXXXX');`}} />
        
        </Head>
        <body className="custom_class">
         {this.props.customValue }
         <Main />
         <NextScript />
       </body>
      </html>
    )
  }
}

MyDocument.propTypes = {
  title: PropTypes.string,
  description: PropTypes.string,
  url: PropTypes.string,
  ogImage: PropTypes.string
}

Because previously I was directly using next/head custom component and it was working properly for each page.But now to use custom addition in Body and Head tag I am using the concept of _document.js page .So need help on how to pass custom props (Title,description,keywords,canonical) as per page navigation

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:10 (3 by maintainers)

github_iconTop GitHub Comments

11reactions
coluccinicommented, Sep 13, 2017

Just define the info that will not change per page inside the <head> in _document and define the ones that do will change inside every page/component using Head component from next/head

2reactions
rupeshdeotale97commented, Sep 18, 2017

@aaawtest To fix this the workaround that I have done was.

In page file I have added below code.

`static async getInitialProps(props) { const { pathname, query, asPath } = props;

return {title:config.title,description:config.description,canonical:config.canonical,keywords:config.keywords}    

}`

And to fetch that information in _document file I have used below code.

`<title>{this.props.NEXT_DATA.props.title || ‘’}</title>

      <meta name="description" content={this.props.__NEXT_DATA__.props.description || defaultDescription} />

      <meta name="keywords" content={this.props.__NEXT_DATA__.props.keywords || ''} />

      <meta name="robots" content="INDEX,FOLLOW" />
      <meta name="HandheldFriendly" content="true" />
      <link rel="canonical" href={this.props.__NEXT_DATA__.props.canonical || ''} />`
Read more comments on GitHub >

github_iconTop Results From Across the Web

Is it possible to pass dynamic props, from one page to another ...
I'm new to Next and have been trying to make a page(index.js) that fetches data(countries) and then displays that data, where each returned ......
Read more >
Displaying Data with Props - From JavaScript to React - Next.js
Using props. In your HomePage component, you can pass a custom title prop to the Header component, just like you'd ...
Read more >
How passing props to component works in React
Master how to pass props (properties) to components in React with this useful beginner's guide, including demo code.
Read more >
Fetch Data in Next.js - Documentation - Prismic
Data returned from a page's getServerSideProps() function will be passed as props to the page's component. This function will run on every page...
Read more >
Props | Vue.js
Prop Passing Details # · Prop Name Casing # · Static vs. Dynamic Props # · Passing Different Value Types # · Binding...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found