반응형
사용자가 입력한 채팅을 저장하는 방법과 화면에 보여주는 방법을 기록하면 나중에 유용하게 사용될 것 같아 이렇게 글을 작성하게 되었습니다.
📌 코드 해석
1. handleChatInput: input의 폼이 변경된 값을 저장하는 역할을 합니다.
2. handleSubmitBtn: 전송 버튼을 눌렀을 때 input의 변경된 값을 chat이라는 state에 저장하고, input을 초기화시켜주는 역할을 수행합니다.
3. ShowChatList(): 사용자가 입력한 메시지를 출력해주는 역할을 하는 컴포넌트 입니다. chat이라는 state를 전달받습니다.
function ShowChat({data, setChatBtn}) {
let [text, setText] = useState('');
let [chat, setChat] = useState([]);
const handleChatInput = (e) => {
setText(e.target.value);
};
const handleSubmitBtn = () => {
let copyChat = [...chat];
if(text != '') {
copyChat.push(text);
setChat(copyChat);
setText('');
}
}
return(
<section className={cn(style.absolute)}>
<article className={cn(style.chatContainer)}>
<header className={cn(style.header)}>
<div className={cn(style.imgContainer)}>
<img src={data.img} alt="상품 이미지" />
</div>
<div className={cn(style.itemInfo)}>
<h2>{data.title}</h2>
<strong>{data.author}</strong>
</div>
<button type="button" className={cn(style.closeBtn)} onClick={() => {setChatBtn(false)}}>
<img src="/public-assets/apply-content/close.png" alt="close button" />
</button>
</header>
<article className={cn(style.chatList)}>
<div className={cn(style.dateContainer)}>
<span className={cn(style.date)}>
<Clock format={'YYYY-MM-DD'} ticking={false} timezone={"Asia/Seoul"} />
</span>
</div>
<section className={cn(style.myChat)}>
{
<ShowChatList chatList={chat} />
}
</section>
</article>
<div className={cn(style.sendContainer)}>
<input type="text" value={text} className={cn(style.inputStyle)} onChange={handleChatInput} placeholder="내용입력" />
<button type="button" onClick={handleSubmitBtn} className={cn(style.sendBtn)}>
<img src="/public-assets/one-content/share.png" alt="share button" />
</button>
</div>
</article>
</section>
);
}
function ShowChatList({chatList}) {
return (
chatList.map((chat, i) => {
return(
<div key={i}>
<article className={cn(style.chatBox)}>
<p className={cn(style.myMsg)}>{chat}</p>
<span className={cn(style.chatTime)}>
<Clock format={'A HH:mm'} ticking={false} timezone={"Asia/Seoul"} />
</span>
</article>
</div>
);
})
);
}
맨 처음 ShowChat이라는 컴포넌트가 전달받은 것들은
1. data: <header> 부분에서 보여줄 데이터를 가지고 있습니다.
2. setChatBtn: 닫기 버튼을 눌렀을 때 해당 state를 false로 만들어서 채팅창이 화면에서 숨기는 역할을 합니다.
📌 결과
728x90
'React JS' 카테고리의 다른 글
Objects are not valid as a React child 에러 처리 (0) | 2023.01.12 |
---|---|
채팅 중복 없이 저장하기 (0) | 2023.01.07 |
react-live-clock 사용하기 (0) | 2023.01.01 |
Cannot update a component while rendering a different component 해결하기 (0) | 2023.01.01 |
관련된 것 끼리 묶어서 보여주기 (useState 사용) (0) | 2022.12.23 |