Troubleshooting Issue: Next.js and Tailwind CSS causing Sanity HTML Content to Display Incorrectly

We have integrated Sanity, Next.js, and Tailwind CSS into our current project. Recently, a field named 'raw_html' has been added to the Sanity content, which includes some HTML code along with sample data.

<div class="p-4 bg-gray-100 rounded-lg">
  <h1 class="text-3xl font-bold mb-4">Hello World</h1>
  <p class="mb-2">This is a paragraph with <span class="text-blue-500">Tailwind CSS</span> classes.</p>
  <ul class="list-disc ml-5">
    <li class="mb-1">First item</li>
    <li class="mb-1">Second item</li>
    <li class="mb-1">Third item</li>
  </ul>
</div>

However, there seems to be an issue with displaying this content on the frontend. The HTML appears fine when directly embedded into the code. Are there any specific reasons for this discrepancy or possible solutions? Thank you in advance.

Provided below is the code snippet:

import { useSite } from '@/app/contexts/SiteContext'; // Make sure the import is correct
function Header() {
    const site = useSite();
    if (!site) return <div>Loading...</div>;
    return (
        <div className="m-10">
            <div className="text-center text-red-500">Tailwind CSS is working!</div>
            <div className="prose max-w-none" dangerouslySetInnerHTML={{ __html: site.header.templateDetails.raw_html }} />
        </div>
    );
}

export default Header;

Answer №1

If you're looking to enhance your website's text formatting, consider using the plugin react-portable-text. By utilizing this plugin, you can easily replace the traditional innerhtml element with the following snippet:

<PortableText 
      content={site.header.templateDetails.raw_html} 
      serializers={{ 
        div: ({ children }) => <div className="p-4 bg-gray-100 rounded-lg">{children}</div>,
        h1: ({ children }) => <h1 className="text-3xl font-bold mb-4">{children}</h1>,
        p: ({ children }) => <p className="mb-2">{children}</p>,
        ul: ({ children }) => <ul className="list-disc ml-5">{children}</ul>,
        li: ({ children }) => <li className="mb-1">{children}</li>,
        someCustomType: YourComponent,
      }}
    />

Don't forget to ensure that tailwindcss is integrated successfully within your project.

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

The function $scope.removeNinja cannot be found

As a beginner in Angular, I encountered an issue while working on a project that involved creating a Directory of ninjas with various functionalities implemented using Angular. Here is a snippet of my HTML file: <!DOCTYPE html> <html lang="en" n ...

Angular2 scripts are failing to load in the web browser

Setting up my index page has been more challenging than I anticipated. Take a look at my browser: https://i.stack.imgur.com/L4b6o.png Here is the index page I'm struggling with: https://i.stack.imgur.com/Op6lG.png I am completely stumped this tim ...

How can I incorporate react-bootstrap (Sass) into a css/scss module within a Next.js project?

Is there a way to customize react-bootstrap (Sass) within a Next.js application? I've been able to do this successfully in React apps, but I'm having trouble replicating it in Next.js. I don't want to apply the customization globally or in _ ...

Nextjs unexpectedly displays blank page upon fetching data from Firebase Firestore without any error messages

I am currently facing an issue when trying to retrieve page details from Firebase Firestore using getStaticPaths and getStaticProps in my Next.js project. Despite following the code structure correctly, I am encountering a scenario where the page appears e ...

Handling multiple post requests for the same route in Node.js

I am in the process of creating a Node JS application utilizing Express JS and MongoDb. Within my index.hjs file (which uses hogan), I have integrated both a login and password recovery feature. Currently, both forms have the action set to "/" and the meth ...

Which is more memory efficient: creating an object with functions defined on it using a function, or creating an instance of a class?

Imagine if I were to create a hypothetical class (this is purely for demonstration purposes) class X { constructor(word, number) { this.wordNumberString = word + number; } saySomething() { return `${this.wordNumberString} ${this.wordNumberStr ...

Tips for retrieving the chosen value from a dropdown list in HTML

I'm having an issue with exporting specific values from multiple HTML tables into an excel file. My goal is to only export the selected values from each table, with each table being on a separate tab in the excel file. Currently, when I export the ta ...

How can I adjust the font size of material-ui buttons while ensuring that they scale appropriately?

Having trouble adjusting the font sizes on Material-UI's RaisedButton for React and ensuring that the button scales properly along with it. <RaisedButton label={<span className="buttonText">Log in Here</span>} /> CSS: .buttonText ...

After a period of time since the server has been initialized, the function req.isAuthenticated() no

In my Node.js routes.js file, I have a function implemented to check if a request is isAuthenticated before serving it: function isLoggedIn(req, res, next) { if (req.isAuthenticated()) { console.log('Session Expiry '+req.session.cook ...

Transmitting checkbox selections using Ajax

Here is the original code that I have written. It attempts to post the value of an input for each checked checkbox. <tbody class="myFormSaldo"> <tr> <td> <input name="checkbox['.$i.']" type="chec ...

Make sure to allow the async task to complete before beginning with Angular JS

As I develop an app using MobileFirst v8 and Ionic v1.3.1, I encounter issues with timing in my code execution. Specifically, when the application initiates, the regular ionic angular code within my app.js file runs. This section of the code handles the i ...

Does the first Ajax call always finish first in the order of Ajax calls?

In my code, I have an ajax call that triggers another ajax call based on its return value. The URL parameter of the second call is modified by the output of the first one. These two calls are interrelated as the first call feeds the URL parameter for the s ...

Is the callback for a request always invoked?

When using the npm module request, I often encounter situations where some requests are not called back, leading to various issues. This has raised a question in my mind - is it expected for the request function to always callback? For instance, if my req ...

I am encountering an issue with CreateJS where I receive the error message: "createjs is not defined"

Looking for assistance with my createJS issue. var stage = new createjs.Stage(canvas); Encountering the following error : angular.js:13642 ReferenceError: createjs is not defined, even though I have EaselJS in my bower-components. Appreciate any hel ...

Validating multiple fields that are added dynamically using jQuery

I am facing an issue with form validation using jQuery. The problem is that when one field is valid, the form gets submitted automatically. Here is a link to my code: http://jsfiddle.net/cvL0ymu7/. How can I ensure that all fields are validated before subm ...

Error: Unable to find axios module

screenshot of browser developer tool - network I have embedded the script in my base.pug file script(scr='https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js') Upon loading the page and inspecting the browser developer tool > n ...

Picture in a clear background without any alteration

Is there a way to create a background-color with opacity inside an image without affecting the image itself? The issue lies in the fact that the transparent background-color makes everything underneath it, including text and the image, transparent. Below ...

Synchronize display with data loading

My plan involves executing 2 AJAX calls: Loading a partial HTML template. Fetching JSON data for the template and displaying it within the loaded template. The JSON must be retrieved separately from the template because users might initiate a "refresh" ...

The MIME type 'text/html' is incompatible with stylesheet MIME type and is not supported

I have exhausted all possible solutions for the issue, from specifying the type for <link rel="stylesheet" href="./style.css" /> to using app.use(express.static('public')), but unfortunately, none of them seem to resolve the problem. index ...

The Combo Box Select2 display is not showing correctly

In my web application, I'm dynamically adding new rows to a table using JavaScript. Each row contains an element where data is loaded from the ViewBag, and I also want to apply the Select2 class to this element. Here is the current code snippet: < ...