uiw md reactor editor 사용법
Written by Sangmin on June 20, 2024

React에서 UIW 마크다운 에디터 구현하기
React 애플리케이션에서 마크다운 에디터를 구현하는 것은 매우 유용하다. 사용자가 마크다운 형식으로 콘텐츠를 작성할 수 있게 해주기 때문이다. 이번 코드 변경에서는 @uiw/react-md-editor
라이브러리를 사용하여 마크다운 에디터를 구현했다.
// components/MarkdownEditor.js
import dynamic from 'next/dynamic';
import { Box, Typography, Button } from '@mui/material';
import '@uiw/react-md-editor/markdown-editor.css'
import '../app/styles/MarkdownEditor.css'
import { useState, useEffect } from 'react';
const MDEditor = dynamic(() => import('@uiw/react-md-editor'), {
ssr: false,
});
먼저 필요한 라이브러리와 컴포넌트를 가져온다. dynamic
임포트를 사용하여 서버 사이드 렌더링 시 에러를 방지한다.
const MarkdownEditor = ({ value, onChange }) => {
const [mode, setMode] = useState('edit');
const [editorHeight, setEditorHeight] = useState('');
const customCommands = [];
// ...
}
MarkdownEditor
컴포넌트에서 mode
상태를 사용하여 편집 모드와 미리보기 모드를 전환한다. editorHeight
상태는 미리보기 모드에서 에디터의 높이를 저장한다.
useEffect(() => {
const ref = document.getElementsByClassName('w-md-editor-content')[0]
if (ref) {
const clientHeight = ref.clientHeight
setEditorHeight(clientHeight);
}
}, [mode, value]);
useEffect
훅을 사용하여 에디터의 높이를 계산하고 editorHeight
상태에 저장한다. 이렇게 하면 미리보기 모드에서 에디터의 높이가 동적으로 조정된다.
return (
<Box style={{ background: 'none', padding: 0 }}>
<Box display='flex' sx={{ justifyContent: 'flex-end' }}>
<Button onClick={() => changeMode('edit')} sx={{ '&:hover': { backgroundColor: '#252525' } }}>
<Typography sx={buttonStyles('edit')} variant='answer'>Edit</Typography>
</Button>
<Button onClick={() => changeMode('preview')} sx={{ '&:hover': { backgroundColor: '#252525' } }}>
<Typography sx={buttonStyles('preview')} variant='answer'>preview</Typography>
</Button>
</Box>
<MDEditor
value={value}
onChange={onChange}
height={mode == "edit" ? '100%' : editorHeight}
preview={mode}
hideToolbar={true}
/>
</Box>
위 코드에서는 Box
컴포넌트를 사용하여 마크다운 에디터의 레이아웃을 설정하고, Button
컴포넌트를 사용하여 편집 모드와 미리보기 모드를 전환한다. MDEditor
컴포넌트를 사용하여 마크다운 에디터를 렌더링하고, mode
상태에 따라 에디터의 높이와 미리보기 모드를 동적으로 설정한다.