react-schemaorgを使ってJSON-LDをサイトに設定する
JSON-LDはGoogleの検索結果に反映されることもあり、できるだけ対応したい用件ではあります。 Reactを使う場合、 react-schemaorgというGoogleが提供しているライブラリを使うと簡単に実装でき […]
広告ここから
広告ここまで
目次
JSON-LDはGoogleの検索結果に反映されることもあり、できるだけ対応したい用件ではあります。
Reactを使う場合、 react-schemaorgというGoogleが提供しているライブラリを使うと簡単に実装できます。
$ yarn add react-schemaorg schema-dts
Usage
JsonLdタグのitemプロパティにデータを投入します。
import { WebPage, Article } from "schema-dts";
import { JsonLd } from "react-schemaorg";
type Post = {
    author: string;
    title: string;
    content: string;
    excerpt: string;
}
const WebpageContent = ({post}: {
  post: Post
}) => {
  return (
    <JsonLd<WebPage>
      item={{
        "@context": "https://schema.org",
        '@type': 'WebPage',
        author: post.author,
        name: post.title,
        abstract: post.excerpt,
      }}
    />
  )
}
あとは通常のReactコンポーネントと同じように使えばOKです。
const IndexPage = () => {
  const post: Post = {
    author: 'John',
    title: "Hello JSON-LD",
    content: "Welcome to JSON-LD with React world!",
    excerpt: "Simply example of JSON-LD with React application."
  }
  return (
  <Layout>
    <SEO title="Home" />
    <WebpageContent
      post={post}
    />
    <h1>{post.title}</h1>
    <p><small>{post.author}</small></p>
    <p>{post.excerpt}</p>
    <div dangerouslySetInnerHTML={{__html: post.content}}></div>
  </Layout>
  )
}
通常のViewをレンダリングする処理の中に入れれるのが便利ですね。
どう表示されるか
JsonLdコンポーネントはscriptタグとして表示されます。

Rendered HTML
<main>
    <script type="application/ld+json">
        {
            "@context": "https://schema.org",
            "@type": "WebPage",
            "author": "John",
            "name": "Hello JSON-LD",
            "abstract": "Simply example of JSON-LD with React application."
        }
    </script>
    <h1>Hello JSON-LD</h1>
    <p><small>John</small></p>
    <p>Simply example of JSON-LD with React application.</p>
    <div>Welcome to JSON-LD with React world!</div>
</main>
簡単ですね。