Skip to content

Instantly share code, notes, and snippets.

@Sammykhaleel
Last active June 30, 2020 22:09
Show Gist options
  • Save Sammykhaleel/9535bd0ddda8d75c75f7934827624161 to your computer and use it in GitHub Desktop.
Save Sammykhaleel/9535bd0ddda8d75c75f7934827624161 to your computer and use it in GitHub Desktop.
// import React from "react";
// import { StyleSheet, Text, View } from "react-native";
// import Start from "./components/Start";
// import Chat from "./components/Chat";
// import "react-native-gesture-handler";
// import { NavigationContainer } from "@react-navigation/native";
// import { createStackNavigator } from "@react-navigation/stack";
// const Stack = createStackNavigator();
// export default function App() {
// return (
// <NavigationContainer>
// <Stack.Navigator initialRouteName="Start">
// <Stack.Screen name="Start" component={Start} />
// <Stack.Screen name="Chat" component={Chat} />
// </Stack.Navigator>
// </NavigationContainer>
// );
// }
// const styles = StyleSheet.create({
// container: {
// flex: 1,
// backgroundColor: "#fff",
// alignItems: "center",
// justifyContent: "center",
// },
// });
import React from "react";
import { StyleSheet, Text, View } from "react-native";
//Import screens
import Chat from "./components/Chat";
import Start from "./components/Start";
//Import navigation
import { createAppContainer } from "react-navigation";
import { createStackNavigator } from "react-navigation-stack";
const navigator = createStackNavigator({
Start: {
screen: Start,
navigationOptions: {
//hide navigation bar on Start screen
headerShown: false,
},
},
Chat: { screen: Chat },
});
const navigatorContainer = createAppContainer(navigator);
export default navigatorContainer;
import React, { Component } from "react";
import {
StyleSheet,
Text,
View,
Button,
TextInput,
ImageBackground,
Platform,
} from "react-native";
import { GiftedChat, Bubble } from "react-native-gifted-chat";
import KeyboardSpacer from "react-native-keyboard-spacer";
const firebase = require("firebase");
require("firebase/firestore");
export default class Chat extends Component {
//pulling in information from Start.js name/color
static navigationOptions = ({ navigation }) => {
return {
name: navigation.state.params.name,
};
};
constructor(props) {
super(props);
firebase.initializeApp({
apiKey: "AIzaSyD6tm7bDF1j9p19O30iBPC0pnzFz2jZj5g",
authDomain: "mad-chatter-dc59a.firebaseapp.com",
databaseURL: "https://mad-chatter-dc59a.firebaseio.com",
projectId: "mad-chatter-dc59a",
storageBucket: "mad-chatter-dc59a.appspot.com",
messagingSenderId: "528994626501",
appId: "1:528994626501:web:7f91a2b905515885bb39ac",
measurementId: "G-L98KW3DB2N",
});
this.referenceMessageUser = null;
this.referenceMessages = firebase.firestore().collection("messages");
this.state = {
messages: [],
user: {
_id: "",
name: "",
avatar: "",
},
uid: 0,
};
}
// Change bubble colour
renderBubble(props) {
{
/* Colour options
'#e67e22', // carrot
'#2ecc71', // emerald
'#3498db', // peter river
'#8e44ad', // wisteria
'#e74c3c', // alizarin
'#1abc9c', // turquoise
'#2c3e50', // midnight blue
https://coolors.co/ */
}
return (
<Bubble
{...props}
wrapperStyle={{
left: {
backgroundColor: "#8e44ad",
},
right: {
backgroundColor: "#2ecc71",
},
}}
/>
);
}
// Set user ID, name and avatar
setUser = (_id, name = "anonymous") => {
this.setState({
user: {
_id: _id,
name: name,
avatar: "https://placeimg.com/140/140/any",
},
});
};
get user() {
return {
name: this.props.navigation.state.params.name,
_id: this.state.uid,
id: this.state.uid,
};
}
onCollectionUpdate = (querySnapshot) => {
const messages = [];
//go through each document
querySnapshot.forEach((doc) => {
var data = doc.data();
messages.push({
_id: data._id,
text: data.text,
createdAt: data.createdAt.toDate(),
user: data.user,
// messages: data.message,
});
});
this.setState({
messages,
});
};
//adding messages to the database and setting the state of user id
componentDidMount() {
// this.authUnsubscribe = firebase.auth().onAuthStateChanged((user) => {
this.authUnsubscribe = firebase.auth().onAuthStateChanged(async (user) => {
if (!user) {
await firebase.auth().signInAnonymously();
}
//update user state with currently active user data
if (user) {
//do something
//now you are sure that tthere is a user in the if statement
}
this.setState({
uid: user.uid,
loggedInText: "Welcome to Mad Chatter",
});
if (user.uid) {
// Do something
console.log(user.uid);
}
// Will not result in an error
this.referenceMessageUser = firebase.firestore().collection("messages");
this.unsubscribeMessageUser = this.referenceMessageUser.onSnapshot(
this.onCollectionUpdate
);
});
this.setState({
messages: [
{
_id: 1,
text: "Hello developer",
createdAt: new Date(),
user: {
_id: 2,
name: "React Native",
avatar: "https://placeimg.com/140/140/any",
},
},
{
_id: 2,
text:
this.props.navigation.state.params.name + " has entered the chat",
createdAt: new Date(),
system: true,
},
],
});
}
//unmounting
componentWillUnmount() {
this.authUnsubscribe();
this.unsubscribeMessageUser();
}
//Adding messages to the database
addMessage() {
const message = this.state.messages[0];
this.referenceMessages.add({
_id: this.state.messages[0]._id,
text: this.state.messages[0].text || "",
createdAt: this.state.messages[0].createdAt,
user: this.state.messages[0].user,
});
}
// Send message function
onSend(messages = []) {
this.setState(
(previousState) => ({
messages: GiftedChat.append(previousState.messages, messages),
}),
() => this.addMessage()
);
}
render() {
return (
<View
style={{
flex: 1,
justifyContent: "center",
backgroundColor: this.props.navigation.state.params.color,
}}
>
<Text> Hello {this.props.navigation.state.params.name}</Text>
<GiftedChat
messages={this.state.messages}
onSend={(messages) => this.onSend(messages)}
renderBubble={this.renderBubble.bind(this)}
user={this.state.user}
/>
{/* Keyboard spacer for android only. */}
{Platform.OS === "android" ? <KeyboardSpacer /> : null}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1, // Sets the width and height of the device
color: "#FFFFFF",
backgroundColor: "#000000",
},
});
import React, { Component } from "react";
import KeyboardSpacer from "react-native-keyboard-spacer";
import {
StyleSheet,
Text,
View,
Button,
TextInput,
TouchableOpacity,
ImageBackground,
} from "react-native";
export default class Start extends React.Component {
constructor(props) {
super(props);
this.state = { name: "", color: "" }; // creates state for"name" and "color"
}
render() {
return (
<ImageBackground
source={require("../assets/BackgroundImage.png")}
style={styles.backgroundImage}
>
<Text style={styles.appTitle}>Mad Chatter</Text>
<View style={styles.container}>
<TextInput
style={styles.nameBox}
onChangeText={(name) => this.setState({ name })}
value={this.state.name}
placeholder="Enter Name"
placeholderTextColor={"black"}
/>
<Text style={styles.title}>Choose your background colour:</Text>
<View style={styles.colorBackground}>
<TouchableOpacity
onPress={() => this.setState({ color: "#090C08" })}
style={[styles.color1, styles.colorButton]}
/>
<TouchableOpacity
onPress={() => this.setState({ color: "#474056" })}
style={[styles.color2, styles.colorButton]}
/>
<TouchableOpacity
onPress={() => this.setState({ color: "#8A95A5" })}
style={[styles.color3, styles.colorButton]}
/>
<TouchableOpacity
onPress={() => this.setState({ color: "#B9C6AE" })}
style={[styles.color4, styles.colorButton]}
/>
</View>
<Button
style={styles.button}
title="Start Chatting"
onPress={() =>
this.props.navigation.navigate("Chat", {
name: this.state.name,
color: this.state.color,
})
}
/>
</View>
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
width: "88%",
fontSize: 16,
height: "44%",
color: "#000",
marginBottom: 20,
alignItems: "center",
},
backgroundImage: {
flex: 1,
alignItems: "center",
width: "100%",
height: "100%",
},
nameBox: {
fontSize: 22,
fontWeight: "800",
borderWidth: 4,
color: "#000000",
borderColor: "#757083",
width: "88%",
marginBottom: 20,
marginTop: 30,
textAlign: "center",
backgroundColor: "white",
},
button: {
height: 65,
width: "88%",
marginBottom: 20,
textAlign: "center",
alignItems: "center",
justifyContent: "center",
backgroundColor: "#757083",
},
appTitle: {
flex: 1,
fontSize: 45,
marginTop: 60,
color: "#FFFFFF",
fontWeight: "600",
textAlign: "center",
},
text: {
fontSize: 16,
fontWeight: "300",
color: "#757083",
marginTop: 15,
marginLeft: 20,
},
title: {
alignItems: "center",
fontSize: 20,
fontWeight: "600",
color: "#FFFFFF",
textAlign: "center",
},
/*========Background Color Options========*/
colorButton: {
height: 50,
width: 50,
borderRadius: 25,
margin: 10,
},
colorBackground: {
flex: 4,
flexDirection: "row",
justifyContent: "space-between",
alignItems: "flex-start",
margin: 15,
},
color1: {
backgroundColor: "#090C08",
},
color2: {
backgroundColor: "#474056",
},
color3: {
backgroundColor: "#8A95A5",
},
color4: {
backgroundColor: "#B9C6AE",
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment