Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i use application/ld+json in nextjs

I have a Layout in next js and I use Head component . I want to use schema json but I have an error.

This is my code:

<Head>
        <script type="application/ld+json">
          {{
            "@context": "http://schema.org",
            "@type": "Person",
            address: {
              "@type": "PostalAddress",
              addressLocality: "Seattle",
              addressRegion: "WA",
              postalCode: "98052",
              streetAddress: "20341 Whitworth Institute 405 N. Whitworth"
            },
            colleague: [
              "http://www.xyz.edu/students/alicejones.html",
              "http://www.xyz.edu/students/bobsmith.html"
            ],
            email: "mailto:[email protected]",
            image: "janedoe.jpg",
            jobTitle: "Professor",
            name: "Jane Doe",
            telephone: "(425) 123-4567",
            url: "http://www.janedoe.com"
          }}
        </script>
</Head>

and this is my error:

Objects are not valid as a React child (found: object with keys {@context, @type, address, colleague, email, image, jobTitle, name, telephone, url}). 

If you meant to render a collection of children, use an array instead. in script (at Layout.js:130) in head in Head (at _document.js:43) in html in Html (at _document.js:42) in MyDocument in Context.Provider in Context.Provider

Please help!

like image 966
Elyas Pourmotazedy Avatar asked Dec 13 '19 07:12

Elyas Pourmotazedy


3 Answers

You need to use dangerouslySetInnerHTML in order to put your schema data.

<Head>
  <script
    type="application/ld+json"
    dangerouslySetInnerHTML={{ __html: JSON.stringify(structuredData) }}
  />
</Head>
like image 65
felixmosh Avatar answered Oct 21 '22 03:10

felixmosh


const addJsonLd = () => {
  return {
    _html: `
     YOUR JSON OBJECT HERE
    `
  }
}

<Head>
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={addJsonLd()}
      key="item-jsonld"
    />
</Head>

The approach is mentioned in the NextJS docs. Setting Metadata in NextJS Apps

like image 8
YHR Avatar answered Oct 21 '22 03:10

YHR


It's actually recommended to use the Next.js Script component next/script now.

import Script from "next/script";

<Head>
    <Script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonData) }}
    />
</Head>
like image 6
neilge Avatar answered Oct 21 '22 04:10

neilge