Home [React] JSX 문자열 출력 줄바꿈 적용
Post
Cancel

[React] JSX 문자열 출력 줄바꿈 적용


문제

문자열 변수에 줄바꿈 적용을 위해 2가지 방법을 사용했는데 되지 않았다.

1
2
3
4
5
6
7
8
9
10
11
12
// \n 사용
const App = () => {
  const text = "this is\n apple";
  return (
    <div>
      <p>{text}</p>
      {/*this is apple*/}
    </div>
  );
};

export default App;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 백틱(``) 사용
const App = () => {
  const text = `this is 
  apple`;

  return (
    <div>
      <p>{text}</p>
      {/*this is apple*/}
    </div>
  );
};

export default App;

하지만 어째선지 웹에서 줄바꿈이 적용되지 않았다.

이유

JSX에서 {} 안에 들어간 문자열 변수 내에 \n이나 백틱(``)으로 줄바꿈을 포함한 경우, 이 줄바꿈이 HTML 요소 내에서 일반적인 공백으로 처리되어 렌더링된다는 것

해결

  • pre & textarea 태그 사용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const App = () => {
  const text = `this is 
  apple`;

  return (
    <div>
      <pre>{text}</pre>
      {/*this is 
         apple*/}
      <textarea>{text}</textarea>
      {/*this is 
         apple*/}
    </div>
  );
};

export default App;
  • white-space CSS 속성 사용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const App = () => {
  const text = `this is 
  apple`;

  return (
    <div>
      <p style=>{text}</p>
      {/*this is 
         apple*/}
    </div>
  );
};

export default App;

마치며

혹시 잘못된 정보나 궁금하신 게 있다면 편하게 댓글 달아주세요.
지적이나 피드백은 언제나 환영입니다.

This post is licensed under CC BY 4.0 by the author.