From c1a99a74383d545388d79f90baa0996c7b87d5aa Mon Sep 17 00:00:00 2001 From: Liren Date: Thu, 13 Jul 2017 12:38:04 +0800 Subject: [PATCH] Implement local chat feature (without Firebase) --- src/App.js | 18 +++++++++++-- src/chat_form.js | 63 +++++++++++++++++++++++++++++++++++---------- src/chat_message.js | 44 ++++++++++++++++--------------- 3 files changed, 89 insertions(+), 36 deletions(-) diff --git a/src/App.js b/src/App.js index db10e54..e7d2984 100644 --- a/src/App.js +++ b/src/App.js @@ -5,6 +5,20 @@ import Firebase from './firebase' import './App.css' class App extends React.Component { + constructor(props) { + super(props); + this.state = { + messages: [] + } + this.sendMessage = this.sendMessage.bind(this) + } + + sendMessage(messageObj) { + this.setState({ + messages: this.state.messages.concat(messageObj) + }) + } + render() { return (
@@ -12,9 +26,9 @@ class App extends React.Component {
Welcome to this friendly chatroom
- +
- +
diff --git a/src/chat_form.js b/src/chat_form.js index f13d5ef..27538ee 100644 --- a/src/chat_form.js +++ b/src/chat_form.js @@ -1,24 +1,61 @@ import React from 'react' export default class ChatForm extends React.Component { + constructor(props) { + super(props) + this.state = { + user: 'Annonymous', + text: '' + } + this.handleTextInput = this.handleTextInput.bind(this) + this.handleFormSubmit = this.handleFormSubmit.bind(this) + } + + handleTextInput(e) { + this.setState({ + [e.target.name]: e.target.value + }) + } + + handleFormSubmit(e) { + e.preventDefault() + this.props.sendMessage(this.state) + this.setState({text: ''}) + } + render() { return( -
- +
+
+ + + +
says:
- -
says:
- - - - -
+ /> + + + +
+ ) } } \ No newline at end of file diff --git a/src/chat_message.js b/src/chat_message.js index 24bcccc..1f520e5 100644 --- a/src/chat_message.js +++ b/src/chat_message.js @@ -1,30 +1,32 @@ import React from 'react' export default class ChatMessage extends React.Component { - render() { - return( -
- -
-

Liren

- Let's use ReactJS and Firebase to make this chat works! -
- -
-

Tom

- Cool! -
+ scrollToBottom() { + let element = document.getElementById('chat-message-container'); + element.scrollTop = element.scrollHeight; + } -
-

Sheng

- Yeaaboooooiiiiiiiiiiiiii -
+ componentDidMount() { + this.scrollToBottom() + } -
-

Kevin

- As you can see, App component is the parent of ChatForm and ChatMessage components. -
+ componentDidUpdate(prevProps, prevState) { + this.scrollToBottom() + } + render() { + return( +
+ { + this.props.messages.map( (message, index) => { + return( +
+

{message.user}

+ {message.text} +
+ ) + }) + }
) }