Skip to content

Commit

Permalink
Step 6.7: Define onSendMessage callback
Browse files Browse the repository at this point in the history
  • Loading branch information
Urigo committed May 20, 2020
1 parent d75927b commit ea1eb6d
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 5 deletions.
39 changes: 36 additions & 3 deletions src/components/ChatRoomScreen/MessageInput.tsx
Expand Up @@ -2,6 +2,7 @@ import Button from '@material-ui/core/Button';
import SendIcon from '@material-ui/icons/Send';
import React from 'react';
import styled from 'styled-components';
import { useState } from 'react';

const Container = styled.div`
display: flex;
Expand Down Expand Up @@ -39,11 +40,43 @@ const SendButton = styled(Button)`
}
`;

const MessageInput: React.FC = () => {
interface MessageInputProps {
onSendMessage(content: string): any;
}

const MessageInput: React.FC<MessageInputProps> = ({ onSendMessage }) => {
const [message, setMessage] = useState('');

const onKeyPress = (e: any) => {
if (e.charCode === 13) {
submitMessage();
}
};

const onChange = ({ target }: any) => {
setMessage(target.value);
};

const submitMessage = () => {
if (!message) return;

setMessage('');

if (typeof onSendMessage === 'function') {
onSendMessage(message);
}
};

return (
<Container>
<ActualInput type="text" placeholder="Type a message" />
<SendButton variant="contained" color="primary">
<ActualInput
type="text"
placeholder="Type a message"
value={message}
onKeyPress={onKeyPress}
onChange={onChange}
/>
<SendButton variant="contained" color="primary" onClick={submitMessage}>
<SendIcon />
</SendButton>
</Container>
Expand Down
22 changes: 20 additions & 2 deletions src/components/ChatRoomScreen/index.tsx
@@ -1,5 +1,5 @@
import React from 'react';
import { useMemo, useState } from 'react';
import { useCallback, useMemo, useState } from 'react';
import styled from 'styled-components';
import ChatNavbar from './ChatNavbar';
import MessageInput from './MessageInput';
Expand Down Expand Up @@ -71,13 +71,31 @@ const ChatRoomScreen: React.FC<ChatRoomScreenParams> = ({
setChat(chat);
}, [chatId]);

const onSendMessage = useCallback(
(content: string) => {
if (!chat) return null;

const message = {
id: (chat.messages.length + 10).toString(),
createdAt: new Date(),
content,
};

setChat({
...chat,
messages: chat.messages.concat(message),
});
},
[chat]
);

if (!chat) return null;

return (
<Container>
<ChatNavbar chat={chat} history={history} />
{chat.messages && <MessagesList messages={chat.messages} />}
<MessageInput />
<MessageInput onSendMessage={onSendMessage} />
</Container>
);
};
Expand Down

0 comments on commit ea1eb6d

Please sign in to comment.