본문으로 바로가기

 

프로젝트 진행 중 다음과 작성한 게시물을 확인하는 페이지에서 다음과 같이, HTML 요소가 문자열로 출력되는 현상이 있었습니다. 

이렇게 출력되는 이유는, cross-site scripting (XSS) 공격을 막기 위해서입니다.

쉽게 말하면, html 내부 script로 인해 유저의 쿠키 등 개인 정보를 탈취할 수 있기 때문이죠.

 

https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

 

dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM.

In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack.

So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with an __html key, to remind yourself that it’s dangerous. For example:

function createMarkup() {
  return {__html: 'First · Second'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

 

제 프로젝트의 경우 다음과 같이 적용하면 되겠네요

{Post ? (
  <div dangerouslySetInnerHTML={{ __html: Post.contents }}></div>
) : (
  ""
)}

 

 

참고한 글)

 

https://velopert.com/1896


darren, dev blog
블로그 이미지 DarrenKwonDev 님의 블로그
VISITOR 오늘 / 전체