글 목록으로

mdx 블로그 컴포넌트 실험

블로그 mdx 지원 기념 컴포넌트 실험실

💡

이 블로그에서 활용할 수 있는 MDX 컴포넌트들을 실험해보기 위한 게시글입니다.

실용적인 글을 찾고 있다면 넘어가시면 됩니다.

ModCodeBlock, CodeBlock

aws ec2 create-subnet --vpc-id vpc-071ecca730edf705f \     --cidr-block 10.10.0.0/24 \     --availability-zone ap-northeast-1a
*파란색 텍스트를 클릭하면 간편하게 수정 후 복사할 수 있습니다.

위에서 ModCodeBlock를 이용해

vpc-id, cidr-block, availability-zone를 변수로 사용할 수 있다. 이때 사용되는 형식은 이러하다.

<ModCodeBlock template=" aws ec2 create-subnet --vpc-id {{vpc-id}} \ {{%TAB}}--cidr-block {{cidr-block}} \ {{%TAB}}--availability-zone {{availability-zone}}" data={{ "vpc-id": "vpc-071ecca730edf705f", "cidr-block": "10.10.0.0/24", "availability-zone": "ap-northeast-1a", }} />

여기서

{{%TAB}}은 탭을 위해서 추가했다. 이후에 필요한 경우 이러한 기능을 추가할 수 있다.

ModCodeBlock의 특징으로는 어떤 커맨드을 독자가 복사하기 전에 변경하여야 할 값을 간단하게 수정 후에 복사할 수 있다는 것이다.
이렇게 되면 CLI를 중심으로 진행되는 블로그 글을 작성할때 독자가 쉽게 따라할 수 있게 된다.

처음으로 추가된 실용적인 용도의 MDX 컴포넌트이다. 이를 기본적으로 모든 게시글에서 활용할 수 있도록

app/blog/[slug]/post.tsx를 다음과 같이 수정했다.

"use client"; import { CodeBlock, ModCodeBlock } from "@/components/code-block"; import "@/styles/mdx.css"; import { getMDXComponent } from "mdx-bundler/client"; export default function PostContent({ code }: any) { const Component = getMDXComponent(code); return ( <Component components={{ code: ({ children, className }: any) => { const match = /language-(\w+)/.exec(className || ""); const language = match ? match[1] : ""; return <CodeBlock language={language} code={children} />; }, ModCodeBlock, }} /> ); }

이렇게 하면 해당 컴포넌트는 전역적으로 사용할 수 있게 된다. ✨

Heading 1

/** * @param {string} names * @return {Promise<string[]>} */ async function notify(names) { const tags = [] for (let i = 0; i < names.length; i++) { tags.push('@' + names[i]) } await ping(tags) } class SuperArray extends Array { static core = Object.create(null) constructor(...args) { super(...args); } bump(value) { return this.map( x => x == undefined ? x + 1 : 0 ).concat(value) } }
const element = ( <> <Food season={{ sault: <p a={[{}]} />, }} ></Food> {/* jsx comment */} <h1 className="title" data-title="true"> Read{" "} <Link href="/posts/first-post"> <a>this page! - {Date.now()}</a> </Link> </h1> </> );

Heading 2

Paragraphs:

This is a paragraph.

Lists:

  • List item 1

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

    1. test 1

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

    2. test 2

      • List item 2

      • List item 3

        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

        이건 테스트용 코드고

        console.log("Hello, World!");

        그리고 이건 이미지죠

  • List item 2

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.


  1. List item 1

    helloworld is a code block.

    package main import ( "fmt" ) func main() { fmt.Println("Hello, World!") }
  2. List item 2

    • List item 3
    • List item 4

Tables:

HeaderContent
Row 1Cell 1
Row 2Cell 2

Code:

console.log("Hello, World!");

ping google.com

Bold and Italic, Strikethrough

Link

This is a quote.

3. 스타일

This article uses Next.js

시작부터 이 블로그 타이틀에 사용한

컴포넌트를 사용해봤다.

잘 동작하는 것을 보니 MDX가 잘 적용되었다는 걸 알 수 있다.

이제 블로그에서 컴포넌트를 사용할 수 있게 되어 몇가지 실험을 해보고자 한다.

우선 인라인 코드 블럭 테스트

console.log("Hello, World!") 를 해보자. 다음은 일반 코드 블럭 테스트

console.log("Hello, World!")

간단한 버튼 컴포넌트

export function SimpleButton() { const [toggle, setToggle] = useState(false); const [count, setCount] = useState(0); return ( <Button onClick={()=> { setToggle(!toggle); setCount(count + 1); }} > {toggle ? "You pushed me!!" : "Push me!!"} </Button> ); }

ip.minpeter.xyz 서버를 이용한 독자 아이피 조회 컴포넌트

export function Ip() { const [ip, setIp] = useState(""); useEffect(() => { fetch("https://ip.minpeter.xyz/ip").then((res) => res.text().then((ip) => setIp(ip)) ); }, []); return <span>Your IP: {ip ? ip : "Loading..."}</span>; }
Your IP: Loading...

간단한 카운터 컴포넌트

export function Counter() { const [count, setCount] = useState(0); return ( <div className="space-y-2"> <p>Count: {count}</p> <div className="space-x-1"> <Button onClick={()=> setCount(count + 1)}>Count Up</Button> <Button variant={"outline"} onClick={()=> setCount(0)}> Reset </Button> </div> </div> ); }

Count: 0


간단한 되게 좋아하네


이전글 / 다음글