Blog Post

Creating a FAQ React Component to add Google Structured Data

In this post, I want to show you how to create a React component that features a FAQ section to make use of Google's Structured Data.

Google's FAQ structured data is a format that allows you to provide a list of questions and answers on a given topic. This can be used to provide helpful information to users who are searching for answers to common questions. FAQ structured data is typically implemented using a JSON-LD format, which is a format that allows you to embed structured data into a web page.

In this example we'll be using React with NextJS together with react-bootstrap.

Let's take a look at our Requirements:

  • We want a component

  • We want it to take questions and answers as props

  • It should also render and display them in a handsome way

Compile the Structured Data

Let's take a look at Google's official documentation (https://developers.google.com/search/docs/advanced/structured-data/faqpage) and their example of the structured data markup:

Let's recreate this in our React Component. Our approach could look like this:

export default function (props) {
    let mainEntity = [];

    props.questions.map(el => {
        mainEntity.push({
            "@type": "Question",
            "name": el.question,
            "acceptedAnswer": {
                "@type": "Answer",
                "text": el.answer
            }
        })
    })

    const structuredData = {
        "@context": "https://schema.org",
        "@type": "FAQPage",
        "mainEntity": mainEntity
    }
}

Now, let's add our markup to the <Head> section of our website - we'll do so with next/head:

<Head>
       <script
                type="application/ld+json"
                dangerouslySetInnerHTML={{__html: JSON.stringify(structuredData)}}
         />
</Head>

Add some more styling and make it look handsome, here's our full example:

Now, let's use it in a page:

// ...

<RichFAQ questions={[
    {
        "answer": "Sample Answer",
        "question": "Sample Question?"
    },
    {
        "answer": "Sample Answer No 2",
        "question": "Sample Question No 2?"
    }
]
}/>

And - Here we go!

Of course, you can also improve this component further or split up the Markup and rendering sections.