├── .watchmanconfig
├── .gitignore
├── app.json
├── packager-info.json
├── .babelrc
├── components
├── GiftedChatWrapper.js
├── AppComponent.js
└── RegisterOrLogin.js
├── settings.json
├── App.js
├── package.json
├── .flowconfig
├── App.test.js
├── store.js
└── README.md
/.watchmanconfig:
--------------------------------------------------------------------------------
1 | {}
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | .expo/
3 | npm-debug.*
4 | .idea
5 |
--------------------------------------------------------------------------------
/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "expo": {
3 | "sdkVersion": "15.0.0"
4 | }
5 | }
6 |
--------------------------------------------------------------------------------
/packager-info.json:
--------------------------------------------------------------------------------
1 | {
2 | "expoServerPort": null,
3 | "packagerPort": null,
4 | "packagerPid": null
5 | }
--------------------------------------------------------------------------------
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": ["babel-preset-expo"],
3 | "env": {
4 | "development": {
5 | "plugins": ["transform-react-jsx-source"]
6 | }
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/components/GiftedChatWrapper.js:
--------------------------------------------------------------------------------
1 | //for jest mocking, need to put it in a separate module?
2 |
3 | import { GiftedChat } from 'react-native-gifted-chat';
4 |
5 | export default GiftedChat;
--------------------------------------------------------------------------------
/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "hostType": "tunnel",
3 | "lanType": "ip",
4 | "dev": true,
5 | "strict": false,
6 | "minify": false,
7 | "urlType": "exp",
8 | "urlRandomness": null
9 | }
--------------------------------------------------------------------------------
/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { StyleSheet, Text, View } from 'react-native';
3 | import firebase from 'firebase';
4 | import AppComponent from './components/AppComponent'
5 | import Store from './store';
6 |
7 | //Store
8 | const fbApp = firebase.initializeApp({
9 | apiKey: 'yourApiKey',
10 | authDomain: "localhost",
11 | databaseURL: 'https://testing-3bba1.firebaseio.com',
12 | storageBucket: 'testing-3bba1.firebaseio.com'
13 | }, 'chatApp');
14 |
15 | const store = new Store(fbApp);
16 |
17 | export default () =>
18 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "gifted-chat-firebase-mobx",
3 | "version": "0.1.0",
4 | "private": true,
5 | "devDependencies": {
6 | "firebase-server": "^0.9.1",
7 | "jest-expo": "^0.3.0",
8 | "mocker": "^0.1.2",
9 | "react-native-scripts": "0.0.25",
10 | "react-test-renderer": "~15.4.1"
11 | },
12 | "main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
13 | "scripts": {
14 | "start": "react-native-scripts start",
15 | "eject": "react-native-scripts eject",
16 | "android": "react-native-scripts android",
17 | "ios": "react-native-scripts ios",
18 | "test": "node node_modules/jest/bin/jest.js --watch"
19 | },
20 | "jest": {
21 | "preset": "jest-expo"
22 | },
23 | "dependencies": {
24 | "expo": "^15.1.3",
25 | "firebase": "^3.7.3",
26 | "firebase-nest": "^0.5.1",
27 | "mobx": "^3.1.7",
28 | "mobx-firebase-store": "^1.2.0",
29 | "mobx-react": "^4.1.3",
30 | "react": "~15.4.0",
31 | "react-native": "0.42.3",
32 | "react-native-gifted-chat": "^0.1.4"
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/.flowconfig:
--------------------------------------------------------------------------------
1 | [ignore]
2 | ; We fork some components by platform
3 | .*/*[.]android.js
4 |
5 | ; Ignore "BUCK" generated dirs
6 | /\.buckd/
7 |
8 | ; Ignore unexpected extra "@providesModule"
9 | .*/node_modules/.*/node_modules/fbjs/.*
10 |
11 | ; Ignore duplicate module providers
12 | ; For RN Apps installed via npm, "Libraries" folder is inside
13 | ; "node_modules/react-native" but in the source repo it is in the root
14 | .*/Libraries/react-native/React.js
15 | .*/Libraries/react-native/ReactNative.js
16 |
17 | ; Additional create-react-native-app ignores
18 |
19 | ; Ignore duplicate module providers
20 | .*/node_modules/fbemitter/lib/*
21 |
22 | ; Ignore misbehaving dev-dependencies
23 | .*/node_modules/xdl/build/*
24 | .*/node_modules/reqwest/tests/*
25 |
26 | ; Ignore missing expo-sdk dependencies (temporarily)
27 | ; https://github.com/exponent/exponent-sdk/issues/36
28 | .*/node_modules/expo/src/*
29 |
30 | ; Ignore react-native-fbads dependency of the expo sdk
31 | .*/node_modules/react-native-fbads/*
32 |
33 | [include]
34 |
35 | [libs]
36 | node_modules/react-native/Libraries/react-native/react-native-interface.js
37 | node_modules/react-native/flow
38 | flow/
39 |
40 | [options]
41 | module.system=haste
42 |
43 | emoji=true
44 |
45 | experimental.strict_type_args=true
46 |
47 | munge_underscores=true
48 |
49 | module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> 'RelativeImageStub'
50 |
51 | suppress_type=$FlowIssue
52 | suppress_type=$FlowFixMe
53 | suppress_type=$FixMe
54 |
55 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(3[0-8]\\|[1-2][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native_oss[a-z,_]*\\)?)\\)
56 | suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(3[0-8]\\|1[0-9]\\|[1-2][0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native_oss[a-z,_]*\\)?)\\)?:? #[0-9]+
57 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy
58 |
59 | unsafe.enable_getters_and_setters=true
60 |
61 | [version]
62 | ^0.38.0
63 |
--------------------------------------------------------------------------------
/components/AppComponent.js:
--------------------------------------------------------------------------------
1 | import React, { PropTypes } from 'react';
2 | import { StyleSheet, Text, View } from 'react-native';
3 | import GiftedChat from './GiftedChatWrapper';
4 | import RegisterOrLogin from './RegisterOrLogin'
5 | import { inject, Provider, observer } from 'mobx-react/native';
6 | import { createAutoSubscriber } from 'firebase-nest';
7 |
8 | //Chat component
9 | @observer
10 | class ChatComponent extends React.Component {
11 | static propTypes = {
12 | store: PropTypes.object.isRequired
13 | }
14 |
15 | onLoadEarlier = () => {
16 | this.props.store.increaseLimitToBy(2);
17 | }
18 |
19 | onSend = (messages = []) => {
20 | const { store } = this.props;
21 | Promise.all(
22 | messages.map(({text, user, createdAt}) =>
23 | store.addMessage({text, uid: user._id || '0', timestamp: new Date(createdAt).getTime()}))
24 | ).catch((e) => alert('error sending message: ' + e.code))
25 | }
26 |
27 | renderError = () => {
28 | const { _autoSubscriberError: fetchError } = this.state;
29 | return {fetchError}
30 | }
31 |
32 | render() {
33 | const { store } = this.props;
34 | const isLoggedIn = !!store.getAuthUser();
35 | const { _autoSubscriberFetching: fetching, _autoSubscriberError: fetchError } = this.state;
36 | const messages = store.messagesInGiftedChatFormat;
37 | const loginComponentHeight = isLoggedIn ? 70 : 240;
38 | return (
39 |
40 |
41 |
42 |
43 | {isLoggedIn &&
44 |
45 |
56 |
57 | }
58 |
59 | )
60 | }
61 | }
62 |
63 | //Auto-subscriber Chat
64 | const Chat = inject('store')(createAutoSubscriber({
65 | getSubs: (props, state) => props.store.getAuthUser() ? props.store.limitedMessagesSub() : [],
66 | subscribeSubs: (subs, props, state) => props.store.subscribeSubsWithPromise(subs)
67 | })(ChatComponent))
68 |
69 | export default class AppComponent extends React.Component {
70 | static propTypes = {
71 | store: PropTypes.object.isRequired
72 | }
73 |
74 | render() {
75 | return (
76 |
77 |
78 |
79 | );
80 | }
81 | }
--------------------------------------------------------------------------------
/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import firebase from 'firebase';
3 | import renderer from 'react-test-renderer';
4 | import FirebaseServer from 'firebase-server';
5 | import AppComponent from './components/AppComponent';
6 | import Store from './store';
7 |
8 | //NOTE: Requires entry to be added to your host file (e.g. /etc/hosts)
9 | //127.0.0.1 localhost.firebaseio.test
10 |
11 | //fixes "addEventListener and attachEvent not available" error
12 | jest.mock('firebase/auth-node', ((...args) => {
13 | return {}
14 | }));
15 |
16 | //https://github.com/mobxjs/mobx-react/issues/186
17 | //https://wietse.loves.engineering/using-jest-with-react-native-and-mobx-34949ea7d2cf#.v11m3rh84
18 | jest.mock('mobx-react/native', () => require('mobx-react/custom'));
19 |
20 | // real GiftedChat doesn't get the onLayout event which is required for it to render messages
21 | jest.mock('./components/GiftedChatWrapper', () => {
22 | const actual = require.requireActual('./components/GiftedChatWrapper');
23 | const React = require('react');
24 | class MyGiftedChat extends React.Component {
25 | render() {
26 | const messages = (this.props.messages || []).map(message => message.text + ' GIFTEDMOCK '+message.user.name).join('\n');
27 | return React.createElement('Text', {name:'MockedGiftedChat'}, [messages]);
28 | }
29 | }
30 | MyGiftedChat.propTypes = actual.propTypes;
31 | return MyGiftedChat;
32 | });
33 |
34 |
35 | const mockFbData = {
36 | chat: {
37 | messages: {msg1: {text: 'hi', timestamp: 24982749824, uid: 'user1'}},
38 | users: {user1: {first: 'user1First', last: 'user2Last'}}
39 | }
40 | }
41 |
42 | describe('Chat app', () => {
43 | let store, fb, server;
44 |
45 | beforeEach(() => {
46 | //From https://medium.com/@io.marco.valente/testing-firebase-with-mocha-locally-da7920c902f1
47 | const config = {
48 | apiKey: 'fake-api-key-for-testing-purposes-only',
49 | databaseURL: 'ws://localhost.firebaseio.test:5000'
50 | }
51 | server = new FirebaseServer(5000, 'localhost.firebaseio.test', mockFbData);
52 | const fbApp = firebase.initializeApp(config, 'TestingEnvironment');
53 |
54 | store = new Store(fbApp, {limitTo: 10, watchAuth: false} );
55 | store.authUser = {}; //fake being logged in
56 | });
57 |
58 | afterEach(function () {
59 | fb && fb.set(null);
60 | if (server) {
61 | server.close();
62 | server = null;
63 | }
64 | });
65 |
66 | it('renders App without crashing', (done) => {
67 | const rendered = renderer.create();
68 | expect(rendered.toJSON()).toBeTruthy();
69 |
70 | //Wait for data to come in
71 | setTimeout(() => {
72 | const jsonStr = JSON.stringify(rendered);
73 | expect(jsonStr.indexOf('hi GIFTEDMOCK user1First user2Last') >= 0).toBe(true);
74 | done()
75 | }, 100);
76 | });
77 | })
78 |
--------------------------------------------------------------------------------
/store.js:
--------------------------------------------------------------------------------
1 |
2 | import MobxFirebaseStore from 'mobx-firebase-store';
3 | import {action, observable, computed} from 'mobx';
4 | import firebase from 'firebase';
5 |
6 | // Assumes the following firebase data model:
7 | // messages: {key1: {text, timestamp, uid}, key2: {text, timestamp, uid}, ...}
8 | // users: {key1: {last, first}, key2: {last, first}, ...}
9 |
10 |
11 | //Subscriptions
12 | function limitedMessagesSubKey(limitTo) {
13 | return `msgs_limitedTo_${limitTo}`;
14 | }
15 |
16 | function userSubKey(uid) {
17 | return `usr_${uid}`;
18 | }
19 |
20 | export default class Store {
21 | constructor(fbApp, {limitTo = 2, watchAuth = true} = {}) {
22 | this.fbApp = fbApp;
23 |
24 | //unsubscribeDelayMs is an optimization for paging to prevent flickering empty data:
25 | // - give some time for new page to come before unsubscribing/removing data for current page
26 | this.mobxStore = new MobxFirebaseStore(firebase.database(fbApp).ref(), {unsubscribeDelayMs: 1000});
27 |
28 | this.limitTo = limitTo;
29 | this.initialLimitTo = limitTo;
30 |
31 | //AUTH
32 | //TODO figure out when unwatchAuth should be called
33 | if (watchAuth) {
34 | this.unwatchAuth = firebase.auth(this.fbApp).onAuthStateChanged(user => {
35 | this.authUser = user;
36 |
37 | if (!user) {
38 | //reset paging to initial limitTo on logout
39 | this.limitTo = this.initialLimitTo;
40 | }
41 | });
42 | }
43 | }
44 |
45 | cleanup() {
46 | if (this.unwatchAuth) {
47 | this.unwatchAuth();
48 | }
49 | }
50 |
51 | //observables
52 | @observable authUser = null;
53 | @observable limitTo = 2;
54 | @observable prevLimitTo = null;
55 |
56 | //Getters
57 |
58 | getAuthUser() { return this.authUser; }
59 |
60 | @computed get messagesInGiftedChatFormat() {
61 | const { limitTo, prevLimitTo } = this;
62 |
63 | let msgs = this.mobxStore.getData(limitedMessagesSubKey(limitTo));
64 |
65 | //optimization to avoid flickering while paginating - try to get previous subscription's data while we're loading older items
66 | if (!msgs && prevLimitTo) {
67 | msgs = this.mobxStore.getData(limitedMessagesSubKey(prevLimitTo));
68 | }
69 |
70 | if (!msgs) {
71 | return [];
72 | }
73 |
74 | const res = msgs.entries().map((entry) => {
75 | const msgKey = entry[0];
76 | const msg = entry[1];
77 | const uid = msg.uid || null;
78 | const user = (uid ? this.mobxStore.getData(userSubKey(uid)) : null);
79 |
80 | //Gifted message will not update unless msgKey changes. So as user info comes in, add user's info to the message key
81 | const userInfoHash = user ? `${user.get('first')}_${user.get('last')}` : '';
82 |
83 | return {
84 | _id: msgKey + userInfoHash,
85 | text: msg.text || '',
86 | createdAt: new Date(msg.timestamp),
87 | user: {
88 | _id: uid,
89 | name: user ? (user.get('first') + ' ' + user.get('last')) : '. .',
90 | //avatar: 'https://facebook.github.io/react/img/logo_og.png'
91 | }
92 | }
93 | });
94 |
95 | //Show latest messages on the bottom
96 | res.reverse();
97 |
98 | return res;
99 | }
100 |
101 | //Write to firebase
102 | @action
103 | addMessage({text, uid, timestamp}) {
104 | return this.mobxStore.fb.child('chat').child('messages').push({text, uid, timestamp})
105 | }
106 |
107 | //Increase query limit
108 | @action
109 | increaseLimitToBy(incr) {
110 | const prevLimitTo = this.limitTo;
111 | this.limitTo = prevLimitTo + incr;
112 | this.prevLimitTo = prevLimitTo;
113 | }
114 |
115 | //Subscriptions
116 |
117 | subscribeSubsWithPromise(subs) {
118 | return this.mobxStore.subscribeSubsWithPromise(subs);
119 | }
120 |
121 | //Get messages and user for each message
122 | limitedMessagesSub() {
123 | const { limitTo } = this;
124 | const fbRef = this.mobxStore.fb;
125 | return [{
126 | subKey: limitedMessagesSubKey(limitTo),
127 | asList: true,
128 | resolveFirebaseRef: () => fbRef.child('chat/messages').limitToLast(limitTo || 1),
129 | //onData: (type, snapshot) => console.log('got msgs ',type,snapshot.val()),
130 | childSubs: (messageKey, messageData) => !messageData.uid ? [] : [{
131 | subKey: userSubKey(messageData.uid),
132 | asValue: true,
133 | resolveFirebaseRef: () => fbRef.child('chat/users').child(messageData.uid),
134 | //onData: (type, snapshot) => console.log('got user ',type,snapshot.val())
135 | }]
136 | }]
137 | }
138 |
139 | @action
140 | signIn({email, password}) {
141 | return firebase.auth(this.fbApp).signInWithEmailAndPassword(email, password);
142 | }
143 |
144 | @action
145 | createUser({email, password}) {
146 | return firebase.auth(this.fbApp).createUserWithEmailAndPassword(email, password);
147 | }
148 |
149 | @action
150 | signOut() {
151 | return firebase.auth(this.fbApp).signOut();
152 | }
153 |
154 | @action
155 | sendPasswordResetEmail({email}) {
156 | return firebase.auth(this.fbApp).sendPasswordResetEmail(email);
157 | }
158 | }
159 |
--------------------------------------------------------------------------------
/components/RegisterOrLogin.js:
--------------------------------------------------------------------------------
1 | import React, { Component, PropTypes } from 'react';
2 | import { Text, TextInput, View, ScrollView, TouchableOpacity } from 'react-native';
3 | import { inject, observer } from 'mobx-react/native';
4 |
5 | @inject('store')
6 | @observer
7 | export default class RegisterOrLogin extends Component {
8 | static propTypes = {
9 | store: PropTypes.object.isRequired,
10 | onFocus: PropTypes.func,
11 | onBlur: PropTypes.func
12 | }
13 |
14 | state = {
15 | email: '',
16 | password: '',
17 | inProgress: null,
18 | localError: null
19 | }
20 |
21 | resetState = (authError) => {
22 | this.setState({
23 | localError: null,
24 | inProgress: null,
25 | password: '',
26 | authError
27 | });
28 | }
29 |
30 | register = () => {
31 | const {email, password} = this.state;
32 |
33 | if (!email || !password) {
34 | this.setState({
35 | localError: 'Enter email and password'
36 | });
37 | return;
38 | }
39 | const {store} = this.props;
40 | this.setState({localError: null, authError: null, inProgress: 'Registering...'}, () => {
41 | store.createUser({
42 | email,
43 | password
44 | })
45 | .then(() => this.resetState())
46 | .catch(error => this.resetState(error));
47 | });
48 | }
49 |
50 | login = () => {
51 | const {email, password} = this.state;
52 |
53 | if (!email || !password) {
54 | this.setState({
55 | localError: 'Enter email and password'
56 | });
57 | return;
58 | }
59 |
60 | const {store} = this.props;
61 | this.setState({localError: null, authError: null, inProgress: 'Logging In...'}, () => {
62 | store.signIn({
63 | email,
64 | password
65 | })
66 | .then(() => this.resetState())
67 | .catch(error => this.resetState(error));
68 | });
69 | }
70 |
71 | sendPasswordResetEmail = () => {
72 | const {email} = this.state;
73 |
74 | if (!email) {
75 | this.setState({
76 | localError: 'Enter email'
77 | });
78 | return;
79 | }
80 | const {store} = this.props;
81 | this.setState({localError: null, authError: null, inProgress: 'Sending email...'}, () => {
82 | store.sendPasswordResetEmail({
83 | email
84 | })
85 | .then(() => {
86 | this.setState({
87 | inProgress: 'Email Sent!'
88 | }, () => {
89 | setTimeout(() => {
90 | this.resetState();
91 | }, 10000);
92 | });
93 | })
94 | .catch(error => this.resetState(error));
95 | });
96 | }
97 |
98 | logout = () => {
99 | const { store } = this.props;
100 |
101 | this.setState({inProgress: 'Logging Out...'}, () => {
102 | store.signOut()
103 | .then(() => this.resetState())
104 | .catch(error => this.resetState(error));
105 | });
106 | }
107 |
108 | focusOnPassword = () => {
109 | const input = this.refs['pwd'];
110 | if (input) {
111 | input.focus();
112 | }
113 | }
114 |
115 | renderLoginForm() {
116 | const {email, password} = this.state;
117 | return (
118 |
119 | this.setState({email:text})}
126 | placeholder="Email"
127 | keyboardType="email-address"
128 |
129 | returnKeyType='next'
130 | blurOnSubmit={false}
131 | onSubmitEditing={this.focusOnPassword}
132 |
133 | value={email}
134 | clearButtonMode='while-editing'
135 | />
136 |
137 | this.setState({password:text})}
143 | placeholder="Password"
144 | secureTextEntry={true}
145 |
146 | returnKeyType='go'
147 | blurOnSubmit={false}
148 | onSubmitEditing={this.login}
149 |
150 | value={password}
151 | clearButtonMode='while-editing'
152 | />
153 |
154 |
155 |
156 |
157 | Login
158 |
159 |
160 |
161 |
162 | Register
163 |
164 |
165 |
166 |
167 | Send Password Reset Email
168 |
169 |
170 |
171 |
172 | );
173 | }
174 |
175 | renderLogoutButton() {
176 | return (
177 |
178 |
179 | Logout
180 |
181 |
182 | );
183 | }
184 |
185 | render() {
186 | const {localError, inProgress, authError} = this.state;
187 | const {store} = this.props;
188 |
189 | const authUser = store.getAuthUser();
190 |
191 | return (
192 |
193 | {inProgress && {inProgress} }
194 | {localError && {localError} }
195 | {authError && API Error: {JSON.stringify(authError)} }
196 | {authUser && Signed in as {authUser.email} }
197 | {!authUser && this.renderLoginForm() }
198 | {authUser && this.renderLogoutButton()}
199 |
200 | );
201 | }
202 |
203 | }
204 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | #### Gifted Chat example -- using mobx and firebase
4 |
5 | Steps to run in iOS simulator (assuming XCode is installed)
6 | 1. `npm install`
7 | 2. `npm run ios`
8 |
9 | e2e app test included:
10 | `npm test`
11 |
12 |
13 | This project was bootstrapped with [Create React Native App](https://github.com/react-community/create-react-native-app).
14 |
15 | Below you'll find information about performing common tasks. The most recent version of this guide is available [here](https://github.com/react-community/create-react-native-app/blob/master/react-native-scripts/template/README.md).
16 |
17 | ## Table of Contents
18 |
19 | * [Updating to New Releases](#updating-to-new-releases)
20 | * [Available Scripts](#available-scripts)
21 | * [npm start](#npm-start)
22 | * [npm test](#npm-test)
23 | * [npm run ios](#npm-run-ios)
24 | * [npm run android](#npm-run-android)
25 | * [npm run eject](#npm-run-eject)
26 | * [Writing and Running Tests](#writing-and-running-tests)
27 | * [Environment Variables](#environment-variables)
28 | * [Configuring Packager IP Address](#configuring-packager-ip-address)
29 | * [Adding Flow](#adding-flow)
30 | * [Customizing App Display Name and Icon](#customizing-app-display-name-and-icon)
31 | * [Sharing and Deployment](#sharing-and-deployment)
32 | * [Publishing to Expo's React Native Community](#publishing-to-expos-react-native-community)
33 | * [Building an Expo "standalone" app](#building-an-expo-standalone-app)
34 | * [Ejecting from Create React Native App](#ejecting-from-create-react-native-app)
35 | * [Build Dependencies (Xcode & Android Studio)](#build-dependencies-xcode-android-studio)
36 | * [Should I Use ExpoKit?](#should-i-use-expokit)
37 | * [Troubleshooting](#troubleshooting)
38 | * [Networking](#networking)
39 | * [iOS Simulator won't open](#ios-simulator-wont-open)
40 | * [QR Code does not scan](#qr-code-does-not-scan)
41 |
42 | ## Updating to New Releases
43 |
44 | You should only need to update the global installation of `create-react-native-app` very rarely, ideally never.
45 |
46 | Updating the `react-native-scripts` dependency of your app should be as simple as bumping the version number in `package.json` and reinstalling your project's dependencies.
47 |
48 | Upgrading to a new version of React Native requires updating the `react-native`, `react`, and `expo` package versions, and setting the correct `sdkVersion` in `app.json`. See the [versioning guide](https://github.com/react-community/create-react-native-app/blob/master/VERSIONS.md) for up-to-date information about package version compatibility.
49 |
50 | ## Available Scripts
51 |
52 | If Yarn was installed when the project was initialized, then dependencies will have been installed via Yarn, and you should probably use it to run these commands as well. Unlike dependency installation, command running syntax is identical for Yarn and NPM at the time of this writing.
53 |
54 | ### `npm start`
55 |
56 | Runs your app in development mode.
57 |
58 | Open it in the [Expo app](https://expo.io) on your phone to view it. It will reload if you save edits to your files, and you will see build errors and logs in the terminal.
59 |
60 | #### `npm test`
61 |
62 | Runs the [jest](https://github.com/facebook/jest) test runner on your tests.
63 |
64 | #### `npm run ios`
65 |
66 | Like `npm start`, but also attempts to open your app in the iOS Simulator if you're on a Mac and have it installed.
67 |
68 | #### `npm run android`
69 |
70 | Like `npm start`, but also attempts to open your app on a connected Android device or emulator. Requires an installation of Android build tools (see [React Native docs](https://facebook.github.io/react-native/docs/getting-started.html) for detailed setup). We also recommend installing Genymotion as your Android emulator. Once you've finished setting up the native build environment, there are two options for making the right copy of `adb` available to Create React Native App:
71 |
72 | ##### Using Android Studio's `adb`
73 |
74 | 1. Make sure that you can run adb from your terminal.
75 | 2. Open Genymotion and navigate to `Settings -> ADB`. Select “Use custom Android SDK tools” and update with your [Android SDK directory](https://stackoverflow.com/questions/25176594/android-sdk-location).
76 |
77 | ##### Using Genymotion's `adb`
78 |
79 | 1. Find Genymotion’s copy of adb. On macOS for example, this is normally `/Applications/Genymotion.app/Contents/MacOS/tools/`.
80 | 2. Add the Genymotion tools directory to your path (instructions for [Mac](http://osxdaily.com/2014/08/14/add-new-path-to-path-command-line/), [Linux](http://www.computerhope.com/issues/ch001647.htm), and [Windows](https://www.howtogeek.com/118594/how-to-edit-your-system-path-for-easy-command-line-access/)).
81 | 3. Make sure that you can run adb from your terminal.
82 |
83 | #### `npm run eject`
84 |
85 | This will start the process of "ejecting" from Create React Native App's build scripts. You'll be asked a couple of questions about how you'd like to build your project.
86 |
87 | **Warning:** Running eject is a permanent action (aside from whatever version control system you use). An ejected app will require you to have an [Xcode and/or Android Studio environment](https://facebook.github.io/react-native/docs/getting-started.html) set up.
88 |
89 | ## Customizing App Display Name and Icon
90 |
91 | You can edit `app.json` to include [configuration keys](https://docs.expo.io/versions/latest/guides/configuration.html) under the `expo` key.
92 |
93 | To change your app's display name, set the `expo.name` key in `app.json` to an appropriate string.
94 |
95 | To set an app icon, set the `expo.icon` key in `app.json` to be either a local path or a URL. It's recommended that you use a 512x512 png file with transparency.
96 |
97 | ## Writing and Running Tests
98 |
99 | This project is set up to use [jest](https://facebook.github.io/jest/) for tests. You can configure whatever testing strategy you like, but jest works out of the box. Create test files in directories called `__tests__` to have the files loaded by jest. See the [the template project](https://github.com/react-community/create-react-native-app/tree/master/react-native-scripts/template/__tests__) for an example test. The [jest documentation](https://facebook.github.io/jest/docs/getting-started.html) is also a wonderful resource, as is the [React Native testing tutorial](https://facebook.github.io/jest/docs/tutorial-react-native.html).
100 |
101 | ## Environment Variables
102 |
103 | You can configure some of Create React Native App's behavior using environment variables.
104 |
105 | ### Configuring Packager IP Address
106 |
107 | When starting your project, you'll see something like this for your project URL:
108 |
109 | ```
110 | exp://192.168.0.2:19000
111 | ```
112 |
113 | The "manifest" at that URL tells the Expo app how to retrieve and load your app's JavaScript bundle, so even if you load it in the app via a URL like `exp://localhost:19000`, the Expo client app will still try to retrieve your app at the IP address that the start script provides.
114 |
115 | In some cases, this is less than ideal. This might be the case if you need to run your project inside of a virtual machine and you have to access the packager via a different IP address than the one which prints by default. In order to override the IP address or hostname that is detected by Create React Native App, you can specify your own hostname via the `REACT_NATIVE_PACKAGER_HOSTNAME` environment variable:
116 |
117 | Mac and Linux:
118 |
119 | ```
120 | REACT_NATIVE_PACKAGER_HOSTNAME='my-custom-ip-address-or-hostname' npm start
121 | ```
122 |
123 | Windows:
124 | ```
125 | set REACT_NATIVE_PACKAGER_HOSTNAME='my-custom-ip-address-or-hostname'
126 | npm start
127 | ```
128 |
129 | The above example would cause the development server to listen on `exp://my-custom-ip-address-or-hostname:19000`.
130 |
131 | ## Adding Flow
132 |
133 | Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept.
134 |
135 | React Native works with [Flow](http://flowtype.org/) out of the box, as long as your Flow version matches the one used in the version of React Native.
136 |
137 | To add a local dependency to the correct Flow version to a Create React Native App project, follow these steps:
138 |
139 | 1. Find the Flow `[version]` at the bottom of the included [.flowconfig](.flowconfig)
140 | 2. Run `npm install --save-dev flow-bin@x.y.z` (or `yarn add --dev flow-bin@x.y.z`), where `x.y.z` is the .flowconfig version number.
141 | 3. Add `"flow": "flow"` to the `scripts` section of your `package.json`.
142 | 4. Add `// @flow` to any files you want to type check (for example, to `App.js`).
143 |
144 | Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors.
145 | You can optionally use a plugin for your IDE for a better integrated experience.
146 |
147 | To learn more about Flow, check out [its documentation](https://flowtype.org/).
148 |
149 | ## Sharing and Deployment
150 |
151 | Create React Native App does a lot of work to make app setup and development simple and straightforward, but it's very difficult to do the same for deploying to Apple's App Store or Google's Play Store without relying on a hosted service.
152 |
153 | ### Publishing to Expo's React Native Community
154 |
155 | Expo provides free hosting for the JS-only apps created by CRNA, allowing you to share your app through the Expo client app. This requires registration for an Expo account.
156 |
157 | Install the `exp` command-line tool, and run the publish command:
158 |
159 | ```
160 | $ npm i -g exp
161 | $ exp publish
162 | ```
163 |
164 | ### Building an Expo "standalone" app
165 |
166 | You can also use a service like [Expo's standalone builds](https://docs.expo.io/versions/latest/guides/building-standalone-apps.html) if you want to get an IPA/APK for distribution without having to build the native code yourself.
167 |
168 | ### Ejecting from Create React Native App
169 |
170 | If you want to build and deploy your app yourself, you'll need to eject from CRNA and use Xcode and Android Studio.
171 |
172 | This is usually as simple as running `npm run eject` in your project, which will walk you through the process. Make sure to install `react-native-cli` and follow the [native code getting started guide for React Native](https://facebook.github.io/react-native/docs/getting-started.html).
173 |
174 | #### Should I Use ExpoKit?
175 |
176 | If you have made use of Expo APIs while working on your project, then those API calls will stop working if you eject to a regular React Native project. If you want to continue using those APIs, you can eject to "React Native + ExpoKit" which will still allow you to build your own native code and continue using the Expo APIs. See the [ejecting guide](https://github.com/react-community/create-react-native-app/blob/master/EJECTING.md) for more details about this option.
177 |
178 | ## Troubleshooting
179 |
180 | ### Networking
181 |
182 | If you're unable to load your app on your phone due to a network timeout or a refused connection, a good first step is to verify that your phone and computer are on the same network and that they can reach each other. Try opening a web browser on your phone and opening the URL that the packager script prints, replacing `exp://` with `http://`. So, for example, if underneath the QR code in your terminal you see:
183 |
184 | ```
185 | exp://192.168.0.1:19000
186 | ```
187 |
188 | Try opening Safari or Chrome on your phone and loading
189 |
190 | ```
191 | http://192.168.0.1:19000
192 | ```
193 |
194 | If this works, but you're still unable to load your app by scanning the QR code, please open an issue on the [Create React Native App repository](https://github.com/react-community/create-react-native-app) with details about these steps and any other error messages you may have received.
195 |
196 | If you're not able to load the `http` URL in your phone's web browser, try using the tethering/mobile hotspot feature on your phone (beware of data usage, though), connecting your computer to that WiFi network, and restarting the packager.
197 |
198 | ### iOS Simulator won't open
199 |
200 | If you're on a Mac, there are a few errors that users sometimes see when attempting to `npm run ios`:
201 |
202 | * "non-zero exit code: 107"
203 | * "You may need to install Xcode" but it is already installed
204 | * and others
205 |
206 | There are a few steps you may want to take to troubleshoot these kinds of errors:
207 |
208 | 1. Make sure Xcode is installed and open it to accept the license agreement if it prompts you. You can install it from the Mac App Store.
209 | 2. Open Xcode's Preferences, the Locations tab, and make sure that the `Command Line Tools` menu option is set to something. Sometimes when the CLI tools are first installed by Homebrew this option is left blank, which can prevent Apple utilities from finding the simulator. Make sure to re-run `npm/yarn run ios` after doing so.
210 | 3. If that doesn't work, open the Simulator, and under the app menu select `Reset Contents and Settings...`. After that has finished, quit the Simulator, and re-run `npm/yarn run ios`.
211 |
212 | ### QR Code does not scan
213 |
214 | If you're not able to scan the QR code, make sure your phone's camera is focusing correctly, and also make sure that the contrast on the two colors in your terminal is high enough. For example, WebStorm's default themes may [not have enough contrast](https://github.com/react-community/create-react-native-app/issues/49) for terminal QR codes to be scannable with the system barcode scanners that the Expo app uses.
215 |
216 | If this causes problems for you, you may want to try changing your terminal's color theme to have more contrast, or running Create React Native App from a different terminal. You can also manually enter the URL printed by the packager script in the Expo app's search bar to load it manually.
217 |
--------------------------------------------------------------------------------