Rendering Markdown Files in a React App
๐ Summary
In this tutorial, you are going to see how to:
1. Create a new React app.
2. Install the markdown-to-jsx package.
3. Create a Markdown file in the "/public" folder.
4. Create a Markdown renderer component.
5. Use the Markdown renderer component.
๐งฐ Step 1: Create a new React app
- Run the following command to create a new React app:
npx create-react-app app-name
- Replace the "app-name" with the name of your app/project.
- It will take a while since it install all the necessary dependencies.
- Your app is now created, let's navigate into the new app folder and run the command to execute the app:
cd app-name
npm start
- This will start the development server, and you should see an output like this:
You can now view react-app in the browser.
Local: http://localhost:3000
On Your Network: http://---.--.--.-:3000
Note that the development build is not optimized.
To create a production build, use npm run build.
webpack compiled successfully
- Open your browser and head to http://localhost:3000 and you should see the default welcome page!
๐ฆ Step 2: Install the markdown-to-jsx package
Install markdown-to-jsx
to convert Markdown into React-renderable content:
npm install markdown-to-jsx
๐ Step 3: Create a Markdown file in the "/public" folder
Create a folder named "content", if you don't have it yet, in the "public" folder to store your Markdown files.
mkdir public/content
Then add a file like first-post.md
in "public/content/":
# My first post
This is a **Markdown** file rendered in React, and it is:
- Easy to use
- Fun to build
- Supports emojis ๐
๐ผ๏ธ Step 4: Create a Markdown renderer component
Create the MarkdownRenderer.jsx
at the folder "src/components/" and paste the below content:
import React, { useEffect, useState } from 'react';
import Markdown from 'markdown-to-jsx';
export default function MarkdownRenderer({ filePath }) {
const [content, setContent] = useState('');
useEffect(() => {
fetch(filePath)
.then((res) => res.text())
.then((text) => setContent(text));
}, [filePath]);
return <Markdown>{content}</Markdown>;
}
This component fetches the Markdown file and renders it as JSX.
๐งช Step 5: Use the Markdown renderer component
src/App.js
import React from 'react';
import MarkdownRenderer from './components/MarkdownRenderer';
function App() {
return (
<div className="App">
<h1>I'm using the MarkdownRenderer component</h1>
<MarkdownRenderer filePath="/content/first-post.md" />
</div>
);
}
export default App;
Now you just need to start your development server:
npm start
And when you visit http://localhost:3000" your Markdown content is going to be rendered inside your React app!