이번에 작성할 라이브러리는 채팅 UI를 간편하게 구성할 수 있게 해주는 라이브러리이다.
몇가지 종류가 있지만 이번에 사용해볼 chat ui는 @chatscope/chat-ui-kit-react 이다.
1. 라이브러리 설치
우선 라이브러리를 설치해준다.
npm install @chatscope/chat-ui-kit-react
or
yarn add @chatscope/chat-ui-kit-react
2. 기본 사용법
기본적인 사용법은 어렵지 않다.
import React from 'react';
import ReactDOM from 'react-dom';
import {
MainContainer,
ChatContainer,
MessageList,
Message,
MessageInput
} from '@chatscope/chat-ui-kit-react';
import '@chatscope/chat-ui-kit-styles/dist/default/styles.min.css';
const App = () => {
return (
<MainContainer style={{ width: 500, margin: 'auto' }}>
<ChatContainer>
<MessageList>
<Message
model={{
message: '안녕',
direction: 'incoming',
position: 'first',
}}
/>
<Message
model={{
message: '나도 안녕',
direction: 'outgoing',
position: 'first',
}}
/>
</MessageList>
<MessageInput placeholder="메세지 작성" />
</ChatContainer>
</MainContainer>
);
};
위와 같이 큰 형태로 MainContainer, ChatContainer, MessageList, Message, MessageInput으로 나뉜다.
import '@chatscope/chat-ui-kit-styles/dist/default/styles.min.css'; 를 import 하면 기본적은 채팅 프로그램의 스타일을 가져올 수 있다.
위의 형태로 사용 했을 경우 출력되는 화면 이다.
3. 주요 컴포넌트
MainContainer : 채팅 UI의 전체 컨테이너
ChatContainer : 채팅 메세지와 입력필트를 포함하는 컨테이너
MessageList : 메세지 목록을 표시
Message : 메세지를 표시
MessageInput : 사용자가 메세지를 입력할 수 있는 입력 필드
- Message 컴포넌트
가장 많이 사용하는 것중 Message의 설명을 할려고 한다.
Message의 옵션에는 기본적으로 direction과 position은 무조건 입력되어야한다.
direction 은 'incoming'과 'outgoing' 두가지가 있고, 위에 보다시피 incoming은 다른 인원이 보낸것과 같이 출력되고,
outgoing은 본인이 보낸것처럼 표기되게 된다.
position은 'single', 'first', 'nomal', 'last' 4가지가 있고, single은 단일 메세지로 표기, first는 연속된 메세지 그룹의 첫번째, nomal은 중간, last는 마지막 메세지로 표시되게 된다.
글 작성에는 custom이 가능한데, 현재 위의 방식은 Message 자체에 message 옵션을 주어 문자열을 출력한 경우이고,
<Message
model={{
direction: 'incoming',
position: 'single',
}}
>
<Message.TextContent>
<span>안녕</span>
</Message.TextContent>
</Message>
위와 같이 message가 아닌 textContent, customContent 등과 같이 옵션을 추가하여 좀 더 꾸밀 수 있다.
- MessageInput 컴포넌트
messageInput 컴포넌트는 기본적으로 바로 사용이 가능하기에 몇가지 옵션을 표시해줄것이다.
가장 기본적인 메세지 보낼때의 기능은 onSend를 사용하여 보내기 버튼을 눌렀을 때 이벤트를 설정할 수 있다.
<MessageInput
attachButton={false}
onSend={(message) => {
console.log('보내기');
}}
placeholder="메세지 작성"
/>
그리고 위와 같이 기본적으로 사용할 경우 MessageInput에는 첨부파일 표시가 표기된다.
attachButton 옵션을 false로 할경우 첨부파일 표시는 삭제된다.(없을 시 기본은 true 이다.)
이정도가 기본적인 사용법이다. 다음에는 추가로 세부적인 사용법을 알아보자