Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Firebase real-time chatroom app using react class based components
class App extends Component {
constructor() {
super();
this.state = {
joined: false,
nickname: "",
email: "",
msg: "",
messages: {},
};
this.chatRoom = db.ref().child('chatrooms').child('global');
this.handleNewMessages = snap => {
console.log(snap.val());
// if not null then update state
if (snap.val()) this.setState({ messages: snap.val() });
};
}
componentDidMount() {
// subscribe
this.chatRoom.on('value', this.handleNewMessages);
}
componentWillUnmount() {
// unsubscribe
this.chatRoom.off('value', this.handleNewMessages);
}
handleNameChange = e => this.setState({ nickname: e.target.value });
handleEmailChange = e => this.setState({ email: e.target.value });
handleClick = e => {
// register the nickname
db.ref().child('nicknames').push({
nickname: this.state.nickname,
email: this.state.email,
});
this.setState({ joined: true });
};
handleMsgChange = e => this.setState({ msg: e.target.value });
handleKeyDown = e => {
if (e.key === "Enter") {
// send the msg
this.chatRoom.push({
sender: this.state.nickname,
msg: this.state.msg,
});
// clear the field
this.setState({ msg: "" });
}
};
render() {
return (
<div className="App">
{!this.state.joined ? (
<div className="joinForm">
<input placeholder="Nickname" value={this.state.nickname} onChange={this.handleNameChange} /><br />
<input placeholder="Email" value={this.state.email} onChange={this.handleEmailChange} /><br />
<button onClick={this.handleClick}>Join</button>
</div>
) : (
<div className="chat">
<div className="messages">
{Object.keys(this.state.messages).map(message => {
// Check if the msg is from the user
if (this.state.messages[message]["sender"] === this.state.nickname)
return (
<div className="message">
<span id="me">{this.state.messages[message]["sender"]} :</span><br />
{this.state.messages[message]["msg"]}
</div>
);
else
return (
<div className="message">
<span id="sender">{this.state.messages[message]["sender"]} :</span><br />
{this.state.messages[message]["msg"]}
</div>
);
})}
</div>
<input placeholder="msg" onChange={this.handleMsgChange} onKeyDown={this.handleKeyDown} value={this.state.msg} /><br />
</div>
)}
</div>
);
}
}
@joebien

This comment has been minimized.

Copy link

commented May 8, 2019

db not defined

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.