react-markdown 사용하기

mia·2023년 6월 20일
2

플레인 텍스트를 읽기 쉽고 쓰기 쉽게 하자 🔥

마크다운 언어가 만들어지게 된 계기이다.
매번 태그와 함께 작성하는 어려운 방법이 아닌 간단한 문법으로 작성하면 그럴 듯한 문서가 완성된다.
마크다운 문법은 블로그나 리드미 파일을 작성할 때 주로 사용하며 나는 그걸 읽을 수 있는 react-markdown 라이브러리 사용법과 몰랐던 용어들을 정리해보려고 한다.

react-markdown 사용법

설치

$ npm install react-markdown
or
$ yarn add react-markdown

사용

이 패키지의 경우 하나의 리액트 컴포넌트 이다.
하나의 파일로 분리해서 사용하는 것이 나는 조금 더 맞다고 생각하며
만약 Next.JS를 사용한다면 해당 컴포넌트는 SCR로 설정해주어야 한다.

import React from 'react'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'

type Props = {
	text : string;
}

export default function Markdown({text}: Props) {
	return (
    	<ReactMarkdown remarkPlugins={[remarkGfm]}>
        	{text}
      	</ReactMarkdown>
    )
}
)

사용법은 간단하다.
ReactMarkdown이라는 태그로 원하는 text를 감싸주면 된다.
또는 children이라는 속성값에 text를 넣어줄 수도 있다.

remarkGfm

먼저 GFM에 대해 정리해야한다.
GFM이란 Github Flavored Markdown의 약자로 github에서 기존 마크다운에 몇가지 기능을 추가하여 커스터마이징 한 버전이다.
예를들면 테이블, 링크, 테스크리스트 등이 있다.
GFM을 사용하기 위해서는 플러그인을 설치해주어야한다.

설치

$ npm install remark-gfm
or
$ yarn add remark-gfm

사용

위의 예시 참고

syntax-highlighter

여기까지 진행하면 조금은 못생긴 모양의 markdown viewer가 생성된다.
아무런 색이 없어 키워드와 변수들이 잘 구분되지 않는다.
이럴때는 syntax-highlighter를 사용하면 조금 더 이쁘게 커스터마이징 할 수 있다.

설치

$ npm install react-syntax-highlighter
or 
$ yarn add react-syntax-highlighter

사용

import React from 'react'
import ReactMarkdown from 'react-markdown'
import {Prism as SyntaxHighlighter} from 'react-syntax-highlighter'
import {dark} from 'react-syntax-highlighter/dist/esm/styles/prism'
import Image from 'next/image'

type Props = {
	text = string;
}

export default function Markdown({text}: Props) {
	return (
    	<ReactMarkdown
    	components={{
          	// 코드를 어떻게 표현할지에 대한 내용
      		code({node, inline, className, children, ...props}) {
            // markdown에 사용된 언어
        	const match = /language-(\w+)/.exec(className || '')
            // 사용된 언어가 표시되어있는 경우
        	return !inline && match ? (
          	<SyntaxHighlighter
            {...props}
            children={String(children).replace(/\n$/, '')}
            style={dark}
            language={match[1]}
            PreTag="div"
          />
            // 사용된 언어를 따로 적지 않거나 적합하지 않을 경우
        	) : (
          	<code {...props} className={className}>
            {children}
          	</code>
        	)
      	},
          	// nextjs의 경우 img를 Image 컴포넌트로 바꿔줌
        	img: (image) => (
            	<Image
                  src={image.src || ''}
                  alt={image.alt || ''}
                  width={500}
                  height={350}
                  >
            )
    	}}
  	>{text}</ReactMarkdown>
    )
}

ReactMarkdown 태그 안의 component 속성에 위와 같이 적어주면 되는데 마크다운에 사용된 언어를 같이 적어주게 되면 해당 언어에 맞는 highlighter를 보여주도록 한다고 생각하면 된다.
또한 next를 사용할 경우 Image 태그로 이미지를 변경해주는 작업 또한 같이 할 수 있다.
코드의 윗부분은 각 태그들과 키워드들을 어떤 색으로 하이라이팅 해줄지 정해주는 거라면 아래부분은 img태그를 만났을 때 해당 내용을 Image태그로 옮겨달라고 하는 것이다.

profile
노 포기 킾고잉

0개의 댓글