When working with Next.js and fetching content from a WordPress backend, preserving styling applied in the WordPress editor can be crucial for maintaining the visual integrity of your content. One common scenario is when using a WYSIWYG (What You See Is What You Get) editor in WordPress to format text with styling such as bold, italics, or custom fonts.
The Challenge
Consider a situation where you have a blog post stored in WordPress, with certain words or phrases formatted in bold to highlight key points. When fetching this content and rendering it in a Next.js frontend, you want to ensure that the bold styling is preserved.
Solution
To achieve this, you can leverage the dangerouslySetInnerHTML attribute in React. This attribute allows you to render HTML content directly within a component, including any HTML tags and styling applied to the content.
Implementation
Here’s how you can implement this in your Next.js component:
import React from ‘react’;
function BlogPost({ post }) {
return (
<div className=”Blog-post” dangerouslySetInnerHTML={{ __html: post.content }} />
);
}
export default BlogPost;
By using dangerouslySetInnerHTML, you can directly render the HTML content from post.content, preserving any styling applied in the WordPress editor, including bold text.