Frontend/REACT

dangerouslySetInnerHTML 문자열로 출력된 html렌더링 하기 + css를 사용해서 자동 번호 메기기

<zinny/> 2023. 4. 20. 15:33
728x90
const testText = " <ol>
	<li>
    	<p>첫번째 줄 테스트<mark>중요한 부분</mark>입니다.</p>
    </li>
    
    <li>
    	<p>두번째 테스트 에는 중요한게 없습니다.</p>
    </li>
    
    <li>
    	<p><mark>중요한 것은</mark> 아무것도 없습니다</p>
    </li>
</ol> "

작업을 하다보니 문자열에 html이 들어오는 경우가 종종 있다

dangerouslySetInnerHTML을 사용 하면 손쉽게 html을 렌더링 할 수 가 있는데

 

<div dangerouslySetInnerHTML={{ __html: testText }} ></div>

__html을 사용해서 문자열을 넣어주면 html이 렌더링이 된다.

 

하지만 프론트 개발자는 들어온 html에 스타일을 적용해야 하는데 

나는 emottion styled를 이용해보도록 하겠다!

 

 <Contents dangerouslySetInnerHTML={{ __html: warningsHTML }} />
 
 const Contents = styled.div`
  ol {
    display: grid;
    row-gap: 4px;
    counter-reset: number 0;
  }

  li {
    display: flex;
    column-gap: 10px;

    :before {
      counter-increment: number 1;
      content: counter(number) ".";
    }
  }

`;

 

 

넘어 오는 리스트 앞에 순서를 메겨 줘야 하는데 처음에는 백엔드 한테 index를 같이 넘겨달라고 요청했으나

css로 처리 할 수 있는 방법이 있어서 처리 해 보았다

이번 디자인에서는

  • 앞에 숫자만 노출 시키는 경우 
  • 숫자 앞에 0을 붙여서 노출시키는 경우 
  • 숫자 뒤에 .을 붙여서 노출시키는 경우 

의 세가지 상황이 있었다. 

 

숫자만 노출 시키는 경우
const Contents = styled.div`
  ol {
    counter-reset: number 0;
  }

  li {
    :before {
      counter-increment: number 1;
      content: counter(number);
    }
  }
`;
숫자에 0을 붙여서 노출 시키는 경우
const Contents = styled.div`
  ol {
    counter-reset: number 0;
  }

  li {
    :before {
      counter-increment: number 1;
      content: counter(number, decimal-leading-zero);
    }
  }
`;
숫자뒤에 .을 붙여서 노출 시키는 경우
const Contents = styled.div`
  ol {
    counter-reset: number 0;
  }

  li {
    :before {
      counter-increment: number 1;
      content: counter(number) ".";
    }
  }
`;
728x90