Building a Custom Markdown Editor in React With Live Preview
A custom markdown editor is a powerful addition to any developer toolset. In this guide, we'll build one from scratch using React, with real-time preview functionality — perfect for blogs, note apps, or internal tools.
Step 1: Set Up Your React Project
Create your project with Vite or CRA, and install a markdown parser. We'll use marked
:
npx create-react-app markdown-editor
cd markdown-editor
npm install marked
Step 2: Build the Editor Component
Create a new component MarkdownEditor.js
:
import { useState } from "react";
import { marked } from "marked";
function MarkdownEditor() {
const [markdown, setMarkdown] = useState("# Hello, Markdown!");
return (
<div className="flex flex-col md:flex-row gap-4 p-4">
<textarea
value={markdown}
onChange={(e) => setMarkdown(e.target.value)}
className="w-full md:w-1/2 h-96 p-2 border border-gray-300"
/>
<div
className="w-full md:w-1/2 h-96 p-2 border border-gray-300 overflow-auto bg-gray-50"
dangerouslySetInnerHTML={{ __html: marked(markdown) }}
/>
</div>
);
}
export default MarkdownEditor;
Step 3: Render in App
Update your App.js
to use the new editor:
import MarkdownEditor from "./MarkdownEditor";
function App() {
return (
<div className="max-w-6xl mx-auto">
<h1 className="text-2xl font-bold my-4">Custom Markdown Editor</h1>
<MarkdownEditor />
</div>
);
}
export default App;
Step 4: Optional Enhancements
- Add syntax highlighting with
highlight.js
- Support image uploads or export to Markdown files
- Save editor state in localStorage or a database
Conclusion
You now have a basic but functional Markdown editor with live preview in React. This is a great foundation to build more sophisticated writing tools for your personal projects or SaaS ideas.
If this post helped you, consider supporting me: buymeacoffee.com/hexshift
Top comments (0)