소개
이번 글에서는 Draft.js를 사용하여 텍스트 에디터에 키워드 하이라이팅 기능을 구현하는 방법에 대해 알아보겠습니다.
Draft.js는 React를 기반으로 한 강력한 텍스트 에디팅 프레임워크입니다. 우리는 이를 활용하여 사용자가 입력한 문장에서 특정 키워드를 강조하는 기능을 만들어볼 것입니다.
준비물
- React 및 Draft.js 프로젝트
- 키워드 하이라이팅을 위한 CSS 스타일
- 키워드 목록
구현 방법
1. 키워드 목록 작성
우선 키워드를 저장할 배열을 생성하고 우리가 강조할 키워드를 추가합니다.
const keywords = ["Draft.js", "키워드"];
2. 컴포넌트 생성
Draft.js 텍스트 에디터를 사용하기 위해 Editor
및 EditorState
컴포넌트를 import합니다.
import { Editor, EditorState } from 'draft-js';
또한 키워드 하이라이팅을 위한 CSS 스타일을 작성합니다.
.highlight {
background-color: yellow;
}
3. 하이라이팅 로직 구현
우리는 에디터의 콘텐츠가 변경될 때마다 키워드 목록을 참조하여 각 키워드에 대해 하이라이팅을 적용해야 합니다. 이를 위해 Editor
컴포넌트의 onChange
이벤트 핸들러를 작성합니다.
const handleChange = (newEditorState) => {
const contentState = newEditorState.getCurrentContent();
const contentWithKeyword = applyKeywordHighlighting(contentState);
const newEditorStateWithKeyword = EditorState.createWithContent(contentWithKeyword);
setEditorState(newEditorStateWithKeyword);
};
applyKeywordHighlighting
함수는 주어진 콘텐츠 상태에서 키워드 하이라이팅을 적용하는 함수입니다. 이 함수를 구현하기 위해 ContentState
의 .getBlockMap()
메서드를 사용하여 모든 블록을 반복하고 각 블록에 대해 키워드 하이라이팅처리를 수행합니다.
4. 키워드 하이라이팅 적용
위의 applyKeywordHighlighting
함수를 다음과 같이 작성합니다.
const applyKeywordHighlighting = (contentState) => {
let newContentState = contentState;
const blockMap = contentState.getBlockMap();
blockMap.forEach((contentBlock) => {
const text = contentBlock.getText();
keywords.forEach((keyword) => {
const index = text.indexOf(keyword);
if (index !== -1) {
const selection = SelectionState.createEmpty(contentBlock.getKey())
.set('anchorOffset', index)
.set('focusOffset', index + keyword.length);
const contentWithHighlight = Modifier.applyInlineStyle(
newContentState,
selection,
'highlight'
);
newContentState = contentWithHighlight;
}
});
});
return newContentState;
};
위의 함수는 키워드 목록을 반복하며 각 키워드가 텍스트 내에 있는 경우 해당 텍스트를 강조합니다. SelectionState
를 사용하여 각 키워드의 위치를 설정하고 Modifier.applyInlineStyle
을 사용하여 하이라이팅 CSS 클래스를 적용합니다.
5. 코드 실행
위의 로직을 적용한 후, Editor
컴포넌트를 렌더링하여 실행해보면 텍스트 에디터에서 키워드를 입력할 때 해당 키워드가 하이라이팅되는 것을 확인할 수 있습니다.
function App() {
const [editorState, setEditorState] = useState(EditorState.createEmpty());
const handleChange = (newEditorState) => {
const contentState = newEditorState.getCurrentContent();
const contentWithKeyword = applyKeywordHighlighting(contentState);
const newEditorStateWithKeyword = EditorState.createWithContent(contentWithKeyword);
setEditorState(newEditorStateWithKeyword);
};
const applyKeywordHighlighting = (contentState) => {
let newContentState = contentState;
const blockMap = contentState.getBlockMap();
blockMap.forEach((contentBlock) => {
const text = contentBlock.getText();
keywords.forEach((keyword) => {
const index = text.indexOf(keyword);
if (index !== -1) {
const selection = SelectionState.createEmpty(contentBlock.getKey())
.set('anchorOffset', index)
.set('focusOffset', index + keyword.length);
const contentWithHighlight = Modifier.applyInlineStyle(
newContentState,
selection,
'highlight'
);
newContentState = contentWithHighlight;
}
});
});
return newContentState;
};
return (
<div className="App">
<Editor
editorState={editorState}
onChange={handleChange}
/>
</div>
);
}
마치며
이상으로 Draft.js를 이용하여 텍스트 에디터에 키워드 하이라이팅 기능을 구현하기 위한 간단한 방법에 대해 알아보았습니다. 이를 응용하여 사용자 경험을 향상시킬 수 있는 다양한 기능을 추가할 수 있습니다.