Tips for Formatting Your Schema Correctly

Currently, I am working with nextjs and trying to display the Schema inside the head tag. However, when I do so, it displays ":" instead of my intended content.

This is the schema code snippet:

const Schema = (url,image) => (
    <script type="application/ld+json">
      {JSON.stringify({
        "@context": "https://schema.org",
        "@type": "NewsArticle",
        "mainEntityOfPage": {
          "@type": "WebPage",
          "@id": url
        },
        "headline": "Article headline",
        "image": image,
        "datePublished": datePublished,
        "dateModified": dateModified,
        "author": {
          "@type": "Person",
          "name": "****"
        },
        "publisher": {
          "@type": "Organization",
          "name": "macandental",
          "logo": {
            "@type": "ImageObject",
            "url": "***logo.png"
          }
        }
      })}
    </script>
  );
  
  export default Schema; 

Within my component:

  return (
    <>
      <Head>
      <title>{seo.title}</title>
        <meta name="title" content={seo.title} />
        <meta name="description" content={seo.description} />
          <meta property="og:type" content="article" />
          <Schema url={"/faq"}/>
      </Head>
....

Unfortunately, the outcome appears as follows:

<script type="application/ld+json">{&quot;@context&quot;:&quot;https://schema.org&quot;,&quot;@type&quot;:&quot;NewsAr

Answer №1

It has been noted that Next.js escapes certain characters when rendering within the Head component. This issue has been acknowledged in various discussions found here, here, and here.

If you encounter this problem, you can utilize the dangerouslySetInnerHTML prop to directly insert HTML into your component.

Here is an example implementation:

const Schema = (url, image) => {
 const schema = JSON.stringify({
   "@context": "https://schema.org",
   "@type": "NewsArticle",
   "mainEntityOfPage": {
     "@type": "WebPage",
     "@id": url
   },
   // Rest of the JSON-LD schema...
 });

 return (
   <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: schema }} />
 );
};

export default Schema;

This approach aims to prevent Next.js from escaping the JSON-LD schema, allowing it to be rendered correctly as intended.

<script type="application/ld+json">
{
 // Example JSON-LD schema content...
}
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn how to implement IP address ratelimiting with Upstash and Next.js 14 server actions

The question couldn't be simpler, it's all right there in the title of the post. How can I set up rate limiting based on users' IP addresses using Server Actions? I deliberately introduced errors into this code so I could provide a demonst ...

Designing dynamic SVG elements that maintain uniform stroke widths and rounded edges

I'm currently tackling a project that involves creating SVG shapes with strokes that adjust responsively to the size of their parent container. My aim is for these shapes to consistently fill the width and height of the parent container, and I intend ...

The form does not seem to be updating or refreshing even after an AJAX submission and validation

I have a form set up to submit data to my database using jQuery Validate plugin and ajax. However, I'm encountering an issue where after clicking submit, the form does not clear out. While the data does get updated in the database, I need help figurin ...

The persistent state is not being saved correctly by Redux-Persist and is instead returning the initial

I have included redux-persist in my project, but for some reason it is not persisting the state as expected. Instead, I keep receiving the initial state whenever I reload the page. Below is the snippet of my root-reducer: import { combineReducers } from & ...

Layout display issue post redirection in React

I am facing an issue with my app that utilizes styled-components and material-ui. I have set up private routes based on user roles, and when a non-authenticated user is redirected to the login page, the layout fails to load properly. App.tsx import React ...

javascript code producing incorrect HTML

I created a script to populate a selectbox with various options. Initially, the data is in the form of a string like this: "key=value;key2=value2;etc...": //splitting the string to separate different options for the selectbox var values = data.split(&apo ...

What are the steps for utilizing next-connect with a host proxy while working on development tasks?

My backend API server is restinio, and in the past, I used ReactJS for the front-end. To address a proxying issue, I added "proxy": "http://localhost:4000" to my package.json file as explained in this documentation: https://create-react ...

Show or conceal input fields depending on the selection of radio buttons

Hello everyone, I am new to JavaScript and currently learning. Can someone please assist me in fixing this code? The required inputs are: radio-button-1; radio-button-2; input-fields-set-1; input-fields-set-2; input-field-submit. My objective is: Upon ...

Is it possible to utilize localStorage.getItem within Next.js while using redux toolkit?

While I successfully used localStorage.setItem() inside the redux toolkit slice, I encountered an issue when trying to use localStorage.getItem(). The error message "local storage is not defined" popped up, preventing me from accessing the stored data. imp ...

What is the best way to display long text in a browser alert without it being cut off?

Seeking to display a large amount of data in an alert box, but only a portion is currently visible. The following text is all that can be seen: ["19467,1496257152583","19227,1496256651094","19469,1496257033968","17285, ...

Navigating the world of gtag and google_tag_manager: untangling

Tracking custom events in my react application using Google Analytics has been successful. Initially, I followed a helpful document recommending the use of the gtag method over the ga method for logging calls. The implementation through Google Tag Manager ...

Use the `string.replace()` method to swap out strings in a nested object with values from a separate file

Is there a way to swap out the placeholders __fruit_type__, __clothing_type__, __fitness_equipment__, __meditation_app__ in collection.js with the corresponding values from values.js? I'm attempting to do this using the string.replace() Method co ...

PHP is capable of showing echo statements from the function, however it does not directly showcase database information

My current challenge involves using AJAX to pass the ID name of a div as a string in a database query. Despite being able to display a basic text echo from my function, I'm unable to retrieve any content related to the database. // head HTML (AJAX) $( ...

"Explore the convenience of viewing two separate videos on one webpage, each in its own

After extensive research, I have been unable to find any information on the issue at hand. I am attempting to use the jquery plugin OkVideo to display different videos in two separate "section" tags. However, even after explicitly assigning IDs to each con ...

App.controller attributes in HTML tags are not receiving the value of the HTML variable

In the process of developing a simple student-teacher web application, I am utilizing AngularJS to handle the front-end. Within my JavaScript file, there are two app controllers - one for fetching student data and another for retrieving subjects assigned t ...

Is there a way to update a single document in a MongoDB database using Mongoose without directly referencing the document?

Let's say I have an example: 1 //Let's say I have an example 2 3 app.post('/update', validate, async (req, res) => { 4 const {title, description, post_id} = req.body; 5 6 // Updating one of them if they exist 7 ...

Tips for fetching form data transmitted via HTTPS in Node.js?

As someone new to back-end security, I'm hoping for some guidance without judgement: When receiving values over HTTP in my node application, the form data is easily accessible in the request object using req.body.{name of input element} However, whe ...

The ng-controller directive is not functioning accurately

I attempted to execute the following basic HTML: <!DOCTYPE html> <html ng-app="tempApp"> <head> <script src="js_libs/angular/angular.min.js"></script> <script src="js_libs/angular/bootstrap.js"></script&g ...

How can we assign priority to the child element for detection by the "mouseover" event in jQuery?

Can you help me figure out how to make the "mouseover" event prioritize detecting the child element over its parent? This is the jQuery code I've been using: <script> $(function() { $("li").mouseover(function(event){ $('#log&a ...

When adding an object to an array in AngularJS, it seems to trigger updates for

Currently, I am fetching data from a WebAPI and then storing it in an array called products, which is scoped. $scope.products In addition to the products array, I also have another scoped array named selectedFish. $scope.selectedFish = []; My objective ...