[React] 모달창 내부 텍스트 줄바꿈 하기-JS split

박세화·2023년 7월 3일

React JS

목록 보기
10/22
post-thumbnail


시안에 맞춰 작업을 하던 중, 모달 창 내부 텍스트가 캡쳐본처럼 줄바꿈이 되도록 구현해야 했다.
당연히 \n를 쓰면 되겠거니 싶었는데 찾아보니까 JSX 내부에서는 적용이 안된다고 한다.

PasswordPage_login.tsx

<ModalAlert isModalOpen={modalOpen2} close={closeModal2} label={"입력하신 이메일로\n 임시 비밀번호를 전송했습니다:)"} />
  • 일단 label props로 \n을 포함한 텍스트를 받았다.
    지금 이유는 모르겠지만 {} 없이 라벨을 전달하면 split 메소드가 작동을 안한다.

ModalAlert.component.tsx

<Modal.Body className="modal-header border-0 d-flex flex-column justify-content-center align-items-center">
   <Contents>{label.split("\n").map((letter)=>(<>{letter}<br /></>))}</Contents>
   {additional ? <Contents>{additional}</Contents> : null}
</Modal.Body>

Split() 공식문서
The split() method takes a pattern and divides a String
to an ordered list__f substrings by searching for the pattern, puts these substrings into an array, and returns the array.

  • Modal 컴포넌트 내부 받은 label을 처리하는 부분에서 split 메소드는 \n을 기준으로 문자열을 나누고, 양 쪽의 문자열 덩어리로 나눠진 배열을 반환한다.
    (["입력하신 이메일로", "임시 비밀번호를 전송했습니다"])

  • 후에 map 메소드가 배열의 두 원소를 순회하면서 문자열+빈 줄 로 각각의 원소를 교체한다.


이런 거 볼 때마다 순수 자바스크립트 지식이 탄탄해야 함을 느낀다.....😅

0개의 댓글