티스토리 뷰

반응형
Textarea에 폰트 추가 기능을 넣어보자
Textarea에 폰트 추가 기능을 넣어보자

 

실무 중 관리자 기능으로 font 지정과 ul태그의 특정 marker를 추가하는 기능을 구현하게 되었다. document 객체의 getSelection 함수를 사용해야하나 싶었지만 textarea의 ref 객체에 관련 기능이 있었다.

import React, { useState, useRef } from "react";

const MyComponent = () => {
    const [text, setText] = useState("");
    const textareaRef = useRef<HTMLTextAreaElement>(null);

    const PREFIX_BOLD_FONT = `<b style="font-weight: 700;">`;
    const SUFFIX_BOLD_FONT = `</b>`

    const addFont = () => {
        const textarea = textareaRef.current;
        if (!textarea) return;

        /** textarea에서의 selection 시작점 */
        const start = textarea.selectionStart;
        /** textarea에서의 selection 끝지점(블록 지정되어 있는 경우 사용) */
        const end = textarea.selectionEnd;
        const beforeText = text.substring(0, start);
        /** 블록지정되어 있는 text */
        const selectedText = text.substring(start, end);
        const afterText = text.substring(end);
        /** bold stlye이 적용된 html tag를 추가 */
        setText(
            beforeText +
                PREFIX_BOLD_FONT +
                selectedText +
                SUFFIX_BOLD_FONT +
                afterText
        );
        /** 기능 작동 이후 selection을 추가하는 데이터 길이만큼 뒤로 이동*/
        const newCursorPosition =
            start +
            PREFIX_BOLD_FONT.length +
            selectedText.length +
            SUFFIX_BOLD_FONT.length;
        /** textarea로 focus 이동 */
        textarea.focus();
        /** 타이밍 이슈로 1ms만큼 뒤에 수행 */
        setTimeout(() => {
            textarea.setSelectionRange(newCursorPosition, newCursorPosition);
        }, 1);
    };

    return (
        <div>
          <button onClick={addFont}>bold 추가</button>
          <textarea
              value={text}
              onChange={(e) => setText(e.target.value)}
              ref={textareaRef}
          />
        </div>
    );
};

export default MyComponent;
반응형
Total
Today
Yesterday
반응형