개발 이야기/frontend

채팅창 우측 하단부터 메세지 나오게 하기 - flex-direction reverse 사용

thisisamrd 2023. 10. 31.

문제

채팅앱을 구현하던 중, 채팅창 메세지가 사진처럼 우측 위부터 시작해서 나오는 것을 발견했다. 

 

 

이는 어떻게 해결하면 좋을까? 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;
}

 

 

위와 같이 하면 아래처럼 우측 하단부터 메세지가 쌓이는 것을 확인할 수 있다.

 

댓글