Skip to content

Commit

Permalink
rendering external links to new tabs
Browse files Browse the repository at this point in the history
  • Loading branch information
nspilman committed Jan 13, 2024
1 parent f0bcdb9 commit 94f678c
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 17 deletions.
2 changes: 2 additions & 0 deletions package.json
Expand Up @@ -21,7 +21,9 @@
"next": "14.0.4",
"react": "^18",
"react-dom": "^18",
"react-markdown": "^9.0.1",
"remark": "^15.0.1",
"remark-gfm": "^4.0.0",
"remark-html": "^16.0.1",
"tailwind-merge": "^2.2.0",
"tailwindcss-animate": "^1.0.7"
Expand Down
9 changes: 2 additions & 7 deletions src/app/blog/[slug]/page.tsx
@@ -1,5 +1,5 @@
import MarkdownContent from "@/components/RenderMarkdown";
import { getAllPosts, getPostBySlug } from "@/lib/api";
import { markdownToHtml } from "@/lib/utils";
import { formatDateString } from "@/utils";
import { Metadata } from "next";
import Link from "next/link";
Expand Down Expand Up @@ -53,12 +53,7 @@ export default async function Post({ params }: { params: { slug: string } }) {
{formatDateString(date)}
</time>
</header>

<div
id="post-body"
className="p-8"
dangerouslySetInnerHTML={{ __html: await markdownToHtml(html) }}
/>
<MarkdownContent content={html} />
</div>
<ul
style={{
Expand Down
30 changes: 30 additions & 0 deletions src/components/RenderMarkdown.tsx
@@ -0,0 +1,30 @@
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";

// Define a type for the renderer functions
type RendererFunction = (props: any) => JSX.Element;

// Define the renderers with basic types
const renderers: { [nodeType: string]: RendererFunction } = {
a: ({ href, children }) => {
return href.startsWith("https://") ? (
<a href={href} target="_blank" rel="noopener noreferrer">
{children}
</a>
) : (
<a href={href}>{children}</a>
);
},
};

type MarkdownContentProps = {
content: string;
};

const MarkdownContent: React.FC<MarkdownContentProps> = ({ content }) => (
<ReactMarkdown components={renderers as any} remarkPlugins={[remarkGfm]}>
{content}
</ReactMarkdown>
);

export default MarkdownContent;
10 changes: 0 additions & 10 deletions src/lib/utils.ts
@@ -1,16 +1,6 @@
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";

import { remark } from "remark";
import html from "remark-html";

export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}

export async function markdownToHtml(markdown: string) {
const result = await remark()
.use(html, { sanitize: false })
.process(markdown);
return result.toString();
}

0 comments on commit 94f678c

Please sign in to comment.