Skip to content

Instantly share code, notes, and snippets.

@JacobKnaack JacobKnaack/index.js Secret
Last active Jun 14, 2019

Embed
What would you like to do?
Cosmic Messenger chat form parent component
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
You can’t perform that action at this time.