문제
채팅앱을 구현하던 중, 채팅창 메세지가 사진처럼 우측 위부터 시작해서 나오는 것을 발견했다.
이는 어떻게 해결하면 좋을까? ref도 쓰고 높이도 재서 자바스크립트로 구현도 해보았지만, 결국 flex의 기본 개념만 잘 알고 있으면 되었다는 것을 깨달았다.
여기서 사용할 내용은 flex의 row-reverse 및 column-reverse이다.
flex-direction의 reverse 속성
먼저 row-reverse를 설정하면 다음과 같이 행을 기준으로 뒤에서부터 쌓인다.
예시 코드는 이 링크를 참조하자: W3Schools Tryit Editor
W3Schools online HTML editor
The W3Schools online code editor allows you to edit code and view the result in your browser
www.w3schools.com
#main {
width: 400px;
height: 400px;
border: 1px solid #c3c3c3;
display: flex;
flex-direction: row-reverse;
}
그리고 column-reverse를 설정하면 다음과 같이 열을 기준으로 아래서부터 쌓인다.
#main {
width: 400px;
height: 400px;
border: 1px solid #c3c3c3;
display: flex;
flex-direction: column-reverse;
}
코드 구현
해당 개념을 활용하여 아래처럼 코드를 구현할 수 있다.
메세지 영역을 감싸는 wrapper를 적절히 사용해서 row-reverse와 column-reverse를 배치해보자.
<div className='chat-messages-container'>
<div className='messages-wrapper'>
{messages.map((msg, idx) => {
const messageType = msg.senderId === userId ? "me" : "them";
return (
<div className='message-container'>
<div key={idx}>
{msg.content}
</div>
<div className='message-time'>{msg.sendTime}</div>
</div>
);
})}
<div ref={messagesEndRef}></div>
</div>
</div>
.chat-messages-container {
width: 100%;
display: flex;
flex-direction: column-reverse;
background: #d42eda;
height: 426px;
}
.messages-wrapper {
display: flex;
flex-direction: column;
width: 100%;
overflow-y: auto;
/* overflow scroll을 위한 설정 */
max-height: 426px;
background-color: aqua;
}
.message-container {
display: flex;
flex-direction: row-reverse;
background-color: #7090b9;
}
위와 같이 하면 아래처럼 우측 하단부터 메세지가 쌓이는 것을 확인할 수 있다.
'개발 이야기 > frontend' 카테고리의 다른 글
외부 컴포넌트 스타일을 해당 페이지에서 적용하기 위해 className을 넘겨주기 (0) | 2023.11.07 |
---|---|
react에서 css module로 다른 클래스와의 스타일이 충돌되는 것 방지하기 (0) | 2023.11.06 |
React에서 Props 사용하여 공통 컴포넌트 재사용하기 (1) | 2023.10.22 |
React에서 로그인 시 callback으로 WebSocket 상태관리하기 (0) | 2023.10.18 |
Electron 이벤트값을 다르게 설정하여 리액트 컴포넌트 재사용하기 (0) | 2023.10.13 |
댓글