Markdown
The MarkdownComponent is a component designed to render Markdown content as HTML within your Next.js application. It leverages the Showdown library to convert Markdown syntax into HTML, allowing you to easily integrate rich text content. The component also supports additional Markdown features such as tables, automatic links, strikethrough, and task lists. You can dynamically control whether the component is rendered using the remove prop.
Props
- markdown: A string containing the Markdown content that will be converted to HTML.
- remove: A boolean that determines whether the Markdown content should be rendered or not. If
true, the content will not be displayed.
Component Code
src/components/availableComponents/MarkdownComponent.js
import Showdown from 'showdown';
const MarkdownComponent = ({ markdown, remove }) => {
const converter = new Showdown.Converter({
tables: true,
simplifiedAutoLink: true,
strikethrough: true,
tasklists: true,
});
return remove ? null : <div className="markdown" dangerouslySetInnerHTML={{ __html: converter.makeHtml(markdown) }} />;
};
export default MarkdownComponent;`
Component Explanation
-
Markdown to HTML Conversion:
- The component uses the
Showdownlibrary to convert Markdown text into HTML. The conversion process supports extended Markdown features such as tables, simplified auto links, strikethrough, and task lists.
- The component uses the
-
Markdown Features:
- Tables: The
tablesoption enables the rendering of tables written in Markdown syntax. - Simplified Auto Links: The
simplifiedAutoLinkoption automatically converts URLs into clickable links. - Strikethrough: The
strikethroughoption allows for the use of~~to strike through text. - Task Lists: The
tasklistsoption supports the rendering of task lists with checkboxes.
- Tables: The
-
Rendering Process:
- The Markdown content is converted into HTML using
converter.makeHtml(markdown), and the resulting HTML is injected into the DOM usingdangerouslySetInnerHTML. This allows for complex text formatting to be easily handled and displayed.
- The Markdown content is converted into HTML using
-
Visibility Control:
- The component's visibility is controlled by the
removeprop. Ifremoveistrue, the component returnsnull, and the Markdown content is not rendered.
- The component's visibility is controlled by the
Customization
You can customize the MarkdownComponent by:
- Modifying the
markdownprop to render different Markdown content. - Adjusting the configuration of the
Showdownconverter to enable or disable specific Markdown features. - Styling the rendered HTML by adding or modifying CSS classes in the
divcontainer to match your application's design.