เรียนรู้วิธีทำให้ JSON-LD (application/ld+json) schemas ทำงานใน Next.js และโปรเจกต์ ReactJS อื่นๆ
เพื่อ render JSON-LD data ใน Next.js (หรือ React app ใดๆ) คุณต้องใช้:
- อีเลเมนต์
<script> - แอตทริบิวต์
dangerouslySetInnerHTML - เมธอด
JSON.stringify(สำหรับ serialization)
JSON-LD ย่อมาจาก JavaScript Object Notation for Linked Data เป็นวิธีที่เบาเบาในการนำเสนอข้อมูล Schema.org ให้ search engines เกี่ยวกับเนื้อหาของเว็บไซต์
มาดูตัวอย่างกัน
สมมติว่าคุณมี HTML JSON-LD schema โครงสร้างคล้ายนี้:
<script type="application/ld+json">
{
"@context": "https://schema.org/",
"@type": "Product",
"name": "Name of service",
"image": "https://somewebsite.com/static/images/some-image.jpg",
"description": "I seek the means to fight injustice...",
"brand": "Company Name",
"review": {
"@type": "Review",
"name": "Company Name ",
"reviewBody": "It was a dog...",
"reviewRating": { "@type": "Rating", "ratingValue": "5" },
"datePublished": "2020-04-06",
"author": {"@type": "Person", "name": "Emma"}
}
}
</script>
เพื่อให้ JSON-LD schema นี้ทำงานใน Next.js ให้เริ่มด้วยการลบแท็ก HTML <script> ออก เพื่อให้เหลือ JSON-LD object แล้วกำหนดให้ตัวแปร เช่น:
const schemaData = {
"@context": "https://schema.org/",
"@type": "Product",
"name": "Name of service",
"image": "https://somewebsite.com/static/images/some-image.jpg",
"description": "I seek the means to fight injustice...",
"brand": "Company Name",
"review": {
"@type": "Review",
"name": "Company Name ",
"reviewBody": "It was a dog...",
"reviewRating": { "@type": "Rating", "ratingValue": "5" },
"datePublished": "2020-04-06",
"author": {"@type": "Person", "name": "Emma"}
}
};
จากนั้น serialize ตัวแปร schemaData ด้วย JSON.stringify():
JSON.stringify(schemaData)
สุดท้าย ใส่ JSON.stringify(schemaData) เป็นค่า object ของแอตทริบิวต์ dangerouslySetInnerHTML ภายในอีเลเมนต์ <script> เพื่อ render ใน browser:
<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(schemaData) }} />
หากสับสน นี่คือตัวอย่างหน้าเต็มที่ทำงานใน Next.js/React ทุกเว็บไซต์:
import React from 'react';
const schemaData = {
"@context": "https://schema.org/",
"@type": "Product",
"name": "Name of service",
"image": "https://somewebsite.com/static/images/some-image.jpg",
"description": "I seek the means to fight injustice...",
"brand": "Company Name",
"review": {
"@type": "Review",
"name": "Company Name ",
"reviewBody": "It was a dog...",
"reviewRating": { "@type": "Rating", "ratingValue": "5" },
"datePublished": "2020-04-06",
"author": {"@type": "Person", "name": "Emma"}
}
};
const SomePage = () => {
return (
<>
<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(schemaData) }} />
<div>Your content</div>
</>
);
};
export default SomePage;