-
-
Save JacobKnaack/50f60309b13e85ef4a2fab7ed0316ee9 to your computer and use it in GitHub Desktop.
Cosmic Messenger chat form parent component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { Redirect } from 'react-router-dom'; | |
import { socket } from '../../lib/socket.js'; | |
import axios from 'axios'; | |
import { IoIosSend } from "react-icons/io"; | |
import MessageList from './messageList.js'; | |
import UserList from './userList.js'; | |
class Chat extends React.Component { | |
constructor() { | |
super(); | |
this.state = { | |
content: '', | |
selectedUsers: [], | |
} | |
this.handleInput = this.handleInput.bind(this); | |
this.onEnterPress = this.onEnterPress.bind(this); | |
this.handleMessage = this.handleMessage.bind(this); | |
this.handleUserSelect = this.handleUserSelect.bind(this); | |
} | |
componentDidMount() { | |
socket.emit('isOnline', this.props.user); | |
} | |
render() { | |
if (!Object.keys(this.props.user).length) { | |
return <Redirect to='/' /> | |
} | |
return ( | |
<div className="chat-container"> | |
<UserList | |
mobileMenuActive={this.props.mobileMenuActive} | |
handleMobileMenu={this.props.handleMobileMenu} | |
handleLogout={this.props.handleLogout} | |
user={this.props.user} | |
selectedUsers={this.state.selectedUsers} | |
/> | |
<MessageList | |
user={this.props.user} | |
selectedUsers={this.state.selectedUsers} | |
/> | |
<form | |
id="message-input" | |
onSubmit={this.handleMessage} | |
> | |
<textarea | |
className='input-area' | |
name="content" | |
value={this.state.content} | |
onChange={this.handleInput} | |
onKeyDown={this.onEnterPress} | |
placeholder="Send a message ..." | |
/> | |
<button | |
id="send-btn" | |
type="submit" | |
> | |
<IoIosSend /> | |
</button> | |
</form> | |
</div> | |
); | |
} | |
handleInput(e) { | |
const { name, value } = e.target; | |
this.setState({ [name]: value }); | |
} | |
onEnterPress(e) { | |
if (e.keyCode == 13 && e.shiftKey == false) { | |
this.handleMessage(e); | |
} | |
} | |
handleMessage(e) { | |
e.preventDefault(); | |
if (this.state.content) { | |
axios({ | |
method: 'post', | |
url: `${__API_URL__}/message`, | |
headers: { | |
withCredentials: 'true', | |
}, | |
data: { | |
title: this.props.user.name, | |
content: this.state.content, | |
}, | |
}) | |
.then(res => { | |
this.setState({ content: '' }); | |
socket.emit('message', res.data); | |
}) | |
.catch(err => this.setState({ requestError: err })); | |
} | |
} | |
handleUserSelect(user) { | |
this.setState({ | |
selectedUsers: [...this.state.selectedUsers, user] | |
}); | |
} | |
} | |
export default Chat; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment