The Wayback Machine - https://web.archive.org/web/20240717024348/https://www.geeksforgeeks.org/build-a-markdown-previewer/
Open In App

Build a Markdown Previewer

Last Updated : 15 Apr, 2024
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

The Markdown Previewer is a simple web application that allows users to input Markdown syntax and preview the rendered HTML output in real-time. This article will cover the implementation of a Markdown Previewer using HTML, CSS, and JavaScript.Markdown is a lightweight markup language that is commonly used for formatting text on the web.

  • Markdown is a lightweight markup language with plain-text formatting syntax. Common Markdown syntax includes headings, links, inline code, code blocks, lists, blockquotes, images, and emphasis (bold and italic text).
  • The Markdown syntax consists of simple formatting rules such as using # for headers, * or _ for italics, ** or __ for bold, and so on.
  • # Hello, Markdown!’

Approach 1: Vanilla JavaScript Implementation

In this approach, you directly manipulate the DOM elements using JavaScript to capture user input and update the preview container. This approach is suitable for small-scale applications and provides more control over the implementation details.

Explanation:

The provided code demonstrates a basic Markdown Previewer implemented using HTML, CSS, and JavaScript. The HTML file contains text for inputting Markdown syntax and a div element to display the rendered HTML content. JavaScript code listens for input events on the text, converts the Markdown to HTML using the marked library, and updates the preview div accordingly.

Example: Below is an example of building a Markdown Previewer.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>Markdown Previewer</title>
    <link rel="stylesheet" href="styles.css">
</head>

<body>
    <div class="container">
        <div class="editor-container">
            <textarea id="editor"></textarea>
        </div>
        <div class="preview-container">
            <div id="preview"></div>
        </div>
    </div>

    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/marked/2.0.2/marked.min.js"></script>
    <script src="script.js"></script>
</body>

</html>
CSS
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
}

.container {
    display: flex;
    justify-content: space-around;
    align-items: flex-start;
    margin-top: 20px;
}

.editor-container,
.preview-container {
    width: 45%;
}

textarea {
    width: 100%;
    height: 300px;
    border: 1px solid #ccc;
    padding: 10px;
    box-sizing: border-box;
}

#preview {
    border: 1px solid #ccc;
    padding: 10px;
    min-height: 300px;
}
JavaScript
document.addEventListener("DOMContentLoaded", () => {
    const editor = document.getElementById("editor");
    const preview = document.getElementById("preview");

    function updatePreview() {
        const markdown = editor.value;
        const html = marked(markdown, { breaks: true });
        preview.innerHTML = html;
    }

    editor.addEventListener("input", updatePreview);

    // Initial load
    const defaultMarkdown = `
  # Heading 1
  ## Heading 2
  [Link](https://www.example.com)
  \`inline code\`
  \`\`\`
  // Code block
  const greeting = 'Hello';
  console.log(greeting);
  \`\`\`
  - List item 1
  - List item 2
  > Blockquote
  ![Image](https://via.placeholder.com/150)
  **Bold text**
      `;
    editor.value = defaultMarkdown;
    updatePreview();
});

Output:

gfg73

Build a Markdown Previewer

Approach 2: Framework/Library Integration (e.g., React):

Using a framework like React simplifies the development process by providing reusable components, state management, and a virtual DOM for efficient rendering. You can create separate components for the input text and preview container, making the code more modular and maintainable.

Steps to Build a MarkDown Previewer using ReactJS:

Step 1: Create a React app using the following command.

npx create-react-app markdown-previewer
cd markdown-previewer

Step 2: Install the react-markdown library to parse and render Markdown content.

npm install react-markdown

Step 3: Create two components: Editor for inputting Markdown content and Previewer for displaying the parsed Markdown.

Example: Below is an example of MarkDown Previewer using ReactJS.

CSS
.app {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

textarea {
  width: 45%;
  height: 80vh;
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ccc;
}

.preview {
  width: 45%;
  height: 80vh;
  padding: 10px;
  border: 1px solid #ccc;
  overflow-y: auto;
}
JavaScript
// Create the main App component to render 
// both the Editor and Previewer components.
// App.js

import React, { useState } from 'react';
import Editor from './Editor';
import Previewer from './Previewer';
import './App.css';

function App() {
  const [markdown, setMarkdown] = useState('');

  return (
    <div className="app">
      <Editor markdown={markdown} setMarkdown={setMarkdown} />
      <Previewer markdown={markdown} />
    </div>
  );
}

export default App;
JavaScript
//Editor.js

import React from 'react';

function Editor({ markdown, setMarkdown }) {
  return (
    <textarea
      value={markdown}
      onChange={(e) => setMarkdown(e.target.value)}
      placeholder="Enter Markdown here..."
    />
  );
}

export default Editor;
JavaScript
// Previewer.js

import React from 'react';
import ReactMarkdown from 'react-markdown';

function Previewer({ markdown }) {
  return (
    <div>
      <h2>Preview</h2>
      <div className="preview">
        <ReactMarkdown>{markdown}</ReactMarkdown>
      </div>
    </div>
  );
}

export default Previewer;

Start your app using the following command:

npm start

Output:

mark-ezgifcom-video-to-gif-converter

Markdown Previewer Using React



Similar Reads

Rotating 3D Image Previewer Cube using CSS
The 3D Rotating Image Previewer cube is an effect in which a set of images appear on the faces of a revolving 3D cube. This effect can be created using HTML and CSS. Approach: The best way to animate HTML objects is by using CSS @keyframes and by setting transition state at different animation states. HTML Code: Create an HTML File (index.html).Lin
3 min read
Introduction to Markdown
If you have ever worked with git platforms like GitHub, BitBucket or Submitted any question or answers to an online forum, chances are you pretty much have unknowingly used Markdown. Markdown is a lightweight markup language. Created by John Gruber in 2004, Markdown is now one of the world’s most popular markup languages. And given below is a detai
3 min read
How to create links with 'target="_blank"' in Markdown ?
In this article, we will see how to create links with 'target="_blank"' in Markdown. Markdown is a free and open-source lightweight markup language that can be utilized to include formatting elements to plaintext text documents. It is a special way to write words that makes them look different on a computer. For instance, you can make some words lo
4 min read
Primer CSS Markdown
Primer CSS is a free open-source CSS framework built with the GitHub design system to support the broad spectrum of Github websites. It creates the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure that our patterns are steady and interoperable with every other. Its approach to CSS is i
3 min read
Designing a Markdown note taking application in ReactJS
In this article, we will learn how to design a Markdown note-taking application in React that can help one to quickly jot down notes and download the rendered output. The use of Markdown allows one to spend less time on formatting the text and therefore create rich text content using only the Markdown syntax. Prerequisites:NodeJS or NPMReact JSBoot
4 min read
Create a Markdown Editor with live preview using React
In this article, we will be creating a Markdown Editor with a live preview using React. I have used easy-to-understand concepts like functional components and hooks, such as useState, to manage our app's data. Plus, we'll use the handy react-markdown npm package to show Markdown content in our editor. Output Preview: Let us have a look at how the f
3 min read
Markdown Cheat Sheet
Markdown is a simple way to write and format text using plain text symbols. It's a lightweight language that lets you create nicely formatted text without the use of complex coding. The idea is to make it easy for people to read and understand the formatting, even if they're looking at the raw text. This cheat sheet will go over some of the key com
6 min read
Create a Markdown Editor using React Hooks and CodeMirror
Creating a Markdown Editor with React Hooks and CodeMirror is a great way to build a simple yet powerful text editing tool. CodeMirror is a versatile text editor component that can be easily integrated into React applications. Here's a basic example of how you can create a Markdown editor using React Hooks and CodeMirror: Output Preview: Let us hav
4 min read
How to Change HTML Image Size in Markdown ?
In Markdown, you may often find the need to adjust the size of images within your HTML content. Whether you're working on a blog post, documentation, or any other type of content, resizing images can be crucial for maintaining a visually appealing layout. ApproachThis approach involves directly modifying the &lt;img&gt; tag's attributes within the
2 min read
Explain multi-markdown and its usage
MultiMarkdown is an extended form of Markdown syntax, which is a text-to-HTML conversion syntax tool, that allows web writers to write easy to read and write plain text documents and then convert it into an HTML (or, XHTML) document. The design goal for Markdown syntax is to make the code as readable as possible by formatting out the tags and attri
4 min read
Article Tags :
three90RightbarBannerImg