Building a Markdown Editor with React
Building a Markdown Editor with React
Overview
A Markdown editor lets users write formatted text using Markdown syntax and see a live preview of the rendered HTML. Using React, you can create an interactive editor with two main parts:
A textarea for writing Markdown
A preview pane that shows the formatted output
Tools & Libraries
React — for building UI components
marked (or remark) — to parse Markdown into HTML
DOMPurify — to sanitize HTML for security
Step-by-Step Implementation
1. Setup React Project
If you don’t have one yet, create it with Create React App:
bash
Copy
Edit
npx create-react-app markdown-editor
cd markdown-editor
npm install marked dompurify
npm start
2. Create the MarkdownEditor Component
jsx
Copy
Edit
import React, { useState } from 'react';
import { marked } from 'marked';
import DOMPurify from 'dompurify';
export default function MarkdownEditor() {
const [markdown, setMarkdown] = useState('# Hello Markdown!');
// Convert markdown to sanitized HTML
const getMarkdownText = () => {
const rawMarkup = marked(markdown, { breaks: true, gfm: true });
const cleanMarkup = DOMPurify.sanitize(rawMarkup);
return { __html: cleanMarkup };
};
return (
<div style={{ display: 'flex', height: '90vh' }}>
<textarea
style={{ width: '50%', padding: '1rem', fontSize: '1rem' }}
value={markdown}
onChange={(e) => setMarkdown(e.target.value)}
/>
<div
style={{
width: '50%',
padding: '1rem',
borderLeft: '1px solid #ddd',
overflowY: 'auto',
}}
dangerouslySetInnerHTML={getMarkdownText()}
/>
</div>
);
}
3. Use the MarkdownEditor Component
Replace the contents of App.js with:
jsx
Copy
Edit
import React from 'react';
import MarkdownEditor from './MarkdownEditor';
function App() {
return (
<div>
<h1 style={{ textAlign: 'center' }}>React Markdown Editor</h1>
<MarkdownEditor />
</div>
);
}
export default App;
Features You Can Add Next
Toolbar for common Markdown formatting (bold, italic, links)
Save / Load functionality with localStorage or backend
Syntax highlighting with libraries like Prism.js
Split vertical/horizontal view toggle
Mobile responsiveness
Summary
You now have a simple React-based Markdown editor that:
Takes Markdown input from a textarea
Converts it to sanitized HTML using marked and DOMPurify
Displays a live preview side-by-side
Learn MERN Stack Course in Hyderabad
Read More
Building a Responsive Navbar with React
Handling Forms in React with Formik
Using Tailwind CSS in a MERN Stack App
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment