Skip to content

Instantly share code, notes, and snippets.

@ridgeO
Created June 27, 2017 20:19
Show Gist options
  • Save ridgeO/1f609e13227aee5f5b2b23c9cc35c451 to your computer and use it in GitHub Desktop.
Save ridgeO/1f609e13227aee5f5b2b23c9cc35c451 to your computer and use it in GitHub Desktop.
Code snippets from RNFirebaseChat application as featured in http://platypus.is/posts/6
# index.ios.js and index.android.js
import './app.js';
# ./components/firebaseConfig.js
import firebase from "firebase";
// Initialize Firebase
const firebaseConfig = {
apiKey: "<your-api-key>",
authDomain: "<your-auth-domain>",
databaseURL: "<your-database-url>",
storageBucket: "<your-storage-bucket>"
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
export default firebaseApp;
# ./components/SignUp.js
'use strict';
import React, { Component } from 'react';
import {
StatusBar,
KeyboardAvoidingView,
Alert,
Text,
TextInput,
TouchableHighlight
} from 'react-native';
import firebaseApp from './firebaseConfig.js';
import styles from './styles.js';
class SignUp extends Component {
static navigationOptions = {
title: 'SignUp',
header: null
};
render() {
return (
<KeyboardAvoidingView
style={styles.keyboardView}
contentContainerStyle={styles.authContainer}
behavior={'position'}
>
<StatusBar barStyle='light-content'/>
<Text style={styles.appTitle}>Chatypus!</Text>
<Text style={styles.authInputLabel}>Email</Text>
<TextInput
style={styles.authTextInput}
autoCapitalize={'none'}
keyboardType={'email-address'}
placeholder={'[email protected]'}
placeholderTextColor={'#fff'}
/>
<Text style={styles.authInputLabel}>Password</Text>
<TextInput
secureTextEntry={true}
style={styles.authTextInput}
placeholder={'password'}
placeholderTextColor={'#fff'}
/>
<TouchableHighlight style={styles.authButton}
underlayColor={'#1E90FF'}
>
<Text style={styles.authButtonText}>Sign Up</Text>
</TouchableHighlight>
<TouchableHighlight
underlayColor={'#1E90FF'}
>
<Text style={styles.authLowerText}>Go to Sign In</Text>
</TouchableHighlight>
</KeyboardAvoidingView>
)
}
}
export default SignUp;
# ./app.js
'use strict';
import {
AppRegistry
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import SignUp from './components/SignUp.js';
const RootNavigator = StackNavigator(
{
SignUp: { name: 'SignUp', screen: SignUp }
},
{ headerMode: 'screen' }
);
AppRegistry.registerComponent('RNFirebaseChat', () => RootNavigator);
# ./components/SignUp.js
...
constructor(props) {
super(props)
this.state = {
userEmail: '',
userPassword: ''
}
}
...
# ./components/SignUp.js
...
async signUp() {
if (this.state.userEmail != '' && this.state.userPassword != '') {
try {
await firebaseApp.auth().createUserWithEmailAndPassword(this.state.userEmail, this.state.userPassword);
console.log(this.state.userEmail + ' signed up');
} catch(error) {
console.log(error.toString());
Alert.alert(error.toString());
}
}
else {
Alert.alert(
'Invalid Sign Up',
'The Email and Password fields cannot be blank.',
[
{text: 'OK', onPress: () => console.log('OK Pressed')},
],
{ cancelable: false }
)
}
}
...
# ./components/SignUp.js
...
<TouchableHighlight style={styles.authButton}
underlayColor={'#1E90FF'}
onPress={this.signUp.bind(this)}
>
<Text style={styles.authButtonText}>Sign Up</Text>
</TouchableHighlight>
...
# ./components/SignUp.js
...
<Text style={styles.authInputLabel}>Email</Text>
<TextInput
...
onChangeText={(text) => this.setState({ userEmail: text })}
/>
...
<Text style={styles.authInputLabel}>Password</Text>
<TextInput
...
onChangeText={(text) => this.setState({ userPassword: text })}
/>
...
# ./components/SignIn.js
'use strict';
import React, { Component } from 'react';
import {
StatusBar,
KeyboardAvoidingView,
Alert,
Text,
TextInput,
TouchableHighlight
} from 'react-native';
import firebaseApp from './firebaseConfig.js';
import styles from './styles.js';
class SignIn extends Component {
static navigationOptions = {
title: 'SignIn',
header: null
};
constructor(props) {
super(props)
this.state = {
userEmail: '',
userPassword: ''
}
}
async signIn() {
if (this.state.userEmail != '' && this.state.userPassword != '') {
try {
await firebaseApp.auth().signInWithEmailAndPassword(this.state.userEmail, this.state.userPassword);
console.log(this.state.userEmail + ' signed in');
} catch(error) {
console.log(error.toString());
Alert.alert(error.toString());
}
}
else {
Alert.alert(
'Invalid Sign In',
'The Email and Password fields cannot be blank.',
[
{text: 'OK', onPress: () => console.log('OK Pressed')},
],
{ cancelable: false }
)
}
}
render() {
return (
<KeyboardAvoidingView
style={styles.keyboardView}
contentContainerStyle={styles.authContainer}
behavior={'position'}
>
<StatusBar barStyle='light-content'/>
<Text style={styles.appTitle}>Chatypus!</Text>
<Text style={styles.authInputLabel}>Email</Text>
<TextInput
style={styles.authTextInput}
autoCapitalize={'none'}
keyboardType={'email-address'}
placeholder={'[email protected]'}
placeholderTextColor={'#fff'}
onChangeText={(text) => this.setState({ userEmail: text })}
/>
<Text style={styles.authInputLabel}>Password</Text>
<TextInput
secureTextEntry={true}
style={styles.authTextInput}
placeholder={'password'}
placeholderTextColor={'#fff'}
onChangeText={(text) => this.setState({ userPassword: text })}
/>
<TouchableHighlight style={styles.authButton}
underlayColor={'#1E90FF'}
onPress={this.signIn.bind(this)}
>
<Text style={styles.authButtonText}>Sign In</Text>
</TouchableHighlight>
<TouchableHighlight
underlayColor={'#1E90FF'}
>
<Text style={styles.authLowerText}>Go to Sign Up</Text>
</TouchableHighlight>
</KeyboardAvoidingView>
)
}
}
export default SignIn;
# ./app.js
...
import SignIn from './components/SignIn.js';
import SignUp from './components/SignUp.js';
const RootNavigator = StackNavigator(
{
SignIn: { name: 'SignIn', screen: SignIn },
SignUp: { name: 'SignUp', screen: SignUp }
},
...
# ./components/SignIn.js
...
goToSignUp() {
this.props.navigation.navigate('SignUp');
}
...
<TouchableHighlight
...
onPress={() => this.goToSignUp()}
>
<Text style={styles.authLowerText}>Go to Sign Up</Text>
</TouchableHighlight>
...
# ./components/SignUp.js
...
goToSignIn() {
this.props.navigation.goBack();
}
...
<TouchableHighlight
...
onPress={() => this.goToSignIn()}
>
<Text style={styles.authLowerText}>Go to Sign In</Text>
</TouchableHighlight>
...
# ./components/Rooms.js
'use strict'
import React, { Component } from 'react';
import {
Text,
TextInput,
TouchableHighlight,
StatusBar,
ListView,
FlatList,
View
} from 'react-native';
import firebaseApp from './firebaseConfig.js';
import styles from './styles.js';
class Rooms extends Component {
static navigationOptions = {
title: 'Rooms',
header: null
};
renderRow(item) {
return (
<TouchableHighlight style={styles.roomLi}
underlayColor="#fff"
>
<Text style={styles.roomLiText}>{item.name}</Text>
</TouchableHighlight>
)
}
render() {
return (
<View style={styles.roomsContainer}>
<StatusBar barStyle="light-content"/>
<Text style={styles.roomsHeader}>Chatypus</Text>
<View style={styles.roomsInputContainer}>
<TextInput
style={styles.roomsInput}
placeholder={"New Room Name"}
/>
<TouchableHighlight style={styles.roomsNewButton}
underlayColor="#fff"
>
<Text style={styles.roomsNewButtonText}>Create</Text>
</TouchableHighlight>
</View>
<View style={styles.roomsListContainer}>
<FlatList
data={{}}
renderItem={({item}) => (this.renderRow(item)
)}
/>
</View>
</View>
);
}
}
export default Rooms;
# app.js
...
import Rooms from './components/Rooms.js';
...
const RootNavigator = StackNavigator(
{
...
Rooms: { name: 'Rooms', screen: Rooms }
},
...
# ./components/SignIn.js
...
async signIn() {
if (this.state.userEmail != '' && this.state.userPassword != '') {
try {
...
this.props.navigation.navigate('Rooms');
} catch(error) {
...
# ./components/SignUp.js
...
async signUp() {
if (this.state.userEmail != '' && this.state.userPassword != '') {
try {
...
this.props.navigation.navigate('Rooms');
} catch(error) {
...
# ./components/Rooms.js
...
constructor(props) {
super(props);
var firebaseDB = firebaseApp.database();
this.roomsRef = firebaseDB.ref('rooms');
this.state = {
rooms: [],
newRoom: ''
}
}
...
# ./components/Rooms.js
...
componentDidMount() {
this.listenForRooms(this.roomsRef);
}
listenForRooms(roomsRef) {
roomsRef.on('value', (dataSnapshot) => {
var roomsFB = [];
dataSnapshot.forEach((child) => {
roomsFB.push({
name: child.val().name,
key: child.key
});
});
this.setState({ rooms: roomsFB });
});
}
...
# ./components/Rooms.js
...
addRoom() {
if (this.state.newRoom === '') {
return;
}
this.roomsRef.push({ name: this.state.newRoom });
this.setState({ newRoom: '' });
}
...
# ./components/Rooms.js
...
<TextInput
style={styles.roomsInput}
placeholder={"New Room Name"}
onChangeText={(text) => this.setState({newRoom: text})}
value={this.state.newRoom}
/>
<TouchableHighlight style={styles.roomsNewButton}
underlayColor="#fff"
onPress={() => this.addRoom()}
>
...
<FlatList
data={this.state.rooms}
...
# ./components/Messages.js
'use strict'
import React, { Component } from 'react';
import {
StatusBar,
View
} from 'react-native';
import { GiftedChat } from 'react-native-gifted-chat';
import firebaseApp from './firebaseConfig.js';
import styles from './styles.js';
class Messages extends Component {
static navigationOptions = ({ navigation }) => ({
title: 'Messages',
headerStyle: styles.messagesHeader,
headerTitleStyle: styles.messagesTitle,
headerBackTitleStyle: styles.messagesBackTitle
});
render() {
return (
<View style={{flex: 1}}>
<StatusBar barStyle="light-content"/>
<GiftedChat
messages={[]}
onSend={{}}
user={{}}
/>
</View>
);
}
}
export default Messages;
# app.js
...
import Messages from './components/Messages.js';
const RootNavigator = StackNavigator(
{
...
Messages: { name: 'Messages', screen: Messages}
},
...
# ./components/Rooms.js
...
openMessages(room) {
this.props.navigation.navigate('Messages', {roomKey: room.key, roomName: room.name});
}
renderRow(item) {
return (
<TouchableHighlight style={styles.roomLi}
onPress={() => this.openMessages(item)}
...
# ./components/Messages.js
...
static navigationOptions = ({ navigation }) => ({
title: navigation.state.params.roomName,
...
constructor(props) {
super(props);
var FirebaseDB = firebaseApp.database();
var roomKey = this.props.navigation.state.params.roomKey;
this.messagesRef = FirebaseDB.ref(`messages/${roomKey}`);
this.state = {
user: '',
messages: []
}
}
...
# ./components/Messages.js
...
componentDidMount() {
this.setState({ user: firebaseApp.auth().currentUser });
this.listenForMessages(this.messagesRef);
}
listenForMessages(messagesRef) {
messagesRef.on('value', (dataSnapshot) => {
var messagesFB = [];
dataSnapshot.forEach((child) => {
messagesFB = [({
_id: child.key,
text: child.val().text,
createdAt: child.val().createdAt,
user: {
_id: child.val().user._id,
name: child.val().user.name
}
}), ...messagesFB];
});
this.setState({ messages: messagesFB });
});
}
...
# ./components/Messages.js
...
addMessage(message = {}) {
var message = message[0]
this.messagesRef.push({
text: message.text,
createdAt: Date.now(),
user: {
_id: message.user._id,
name: message.user.name
}
})
}
...
# ./components/Messages.js
...
<GiftedChat
messages={this.state.messages}
onSend={this.addMessage.bind(this)}
user={{
_id: this.state.user.uid,
name: this.state.user.email,
}}
/>
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment