[230803] React 개발

React 개발

  • 규칙에 따라 텍스트가 많이 출력되는 프로젝트를 하고 있음
  • bold 처리 등 특정 구간에 문자열을 꾸며줘야함
  • 문자열안에 컴포넌트 형식 넣고 추출하는 헬퍼 함수 만들었다.

parseTextWithComponents 함수

type CustomComponentFunction = (
  tagName: string,
  content: string,
) => React.ReactNode;

const parseTextWithComponents = (
  text: string,
  getCustomComponentFunction: CustomComponentFunction,
): React.ReactNode => {
  const customComponentRegex = /<(\w+)>(.*?)<\/\1>/g;
  const components: React.ReactNode[] = [];

  let lastIndex = 0;
  let match = customComponentRegex.exec(text);

  while (match !== null) {
    const fullMatch = match[0];
    const tagName = match[1];
    const content = match[2];
    const beforeCustomComponent = text.slice(lastIndex, match.index);
    const customComponent = getCustomComponentFunction(tagName, content);

    components.push(beforeCustomComponent);
    components.push(customComponent);

    lastIndex = match.index + fullMatch.length;

    match = customComponentRegex.exec(text);
  }

  if (lastIndex < text.length) {
    const remainingText = text.slice(lastIndex);
    components.push(remainingText);
  }

  return components;
};

사용 예시

  • 쓰고 싶은 컴포넌트에서 getCustomComponent 함수를 정의해준다.
    const getCustomComponent = (
      tagName: string,
      content: string,
    ): React.ReactNode => {
      switch (tagName) {
        case 'BoldText':
          return (
            <PPTFont pt={14} fontColor="#1a4a5d" fontWeight={800}>
              {content}
            </PPTFont>
          );
        default:
          return content;
      }
    };
    
  • 파싱할 텍스트와 커스텀할 함수 넣어주면 됨
    const parseText = parseTextWithComponents(
      "안녕하세요 <BoldText>여긴 진하게</BoldText>해주세요.",
      getCustomComponent,
    );
    
  • 그러면 [여긴 진하게] 부분은 <PPTFont> 컴포넌트에 감쌀 수 있다.

Categories:

Updated:

Leave a comment