Build cross-platform apps with React Native
Learn how to use React Native to build fully functional mobile apps for iOS and Android.
There used to be a time when developers would need to learn Swift/Objective C to build an iOS app, or Java if they wanted to build an Android app. We have now reached an exciting time where web developers can use their existing skills to build both websites and apps without having to learn a completely new language (and a site can be built simply with a website builder).
React Native is a JavaScript library developed by Facebook. It was released back in 2013 and has helped shape apps like Skype, Bloomberg, Wix and many more. Not only can you use your existing knowledge of JavaScript but you can also use the same codebase to build for both iOS and Android.
Building an app in React Native with this tutorial is a great starting point for your own app, and it could easily be improved upon by adding more screens, displaying errors on the front end and much more. You can get the project files you need at Github.
Not quite what you're looking for? See our post full of different tutorials on how to build an app, our pick of the best cloud storage, or, for those running a site, see these website builder options.
01. Get started
To get started building your React Native project, you will need to make sure that you have Node.js installed. You can then install the create-react-native-app command line utility by opening a new a terminal window and running the following command:
npm install -g create-react-native-app
You can then create your new project by running the following command:
create-react-native-app YourAppName
You will then need to navigate to your folder via the command line and start the development server.
Get the Creative Bloq Newsletter
Daily design news, reviews, how-tos and more, as picked by the editors.
cd myNewApp
npm start
You can then begin working on your app by opening the App.js file using a code editor.
02. Run your app
Since you used create-react-native-app via the command line to build your project, you can use the Expo client app to test your application. All you need to do is download the app from the iOS App Store or Google Play Store and then scan the QR code from inside the terminal. You will need to make sure your device is on the same Wi-Fi network as your computer. You can also use the iPhone or Android simulator, if you have Xcode or Android Studio installed.
03. Create a basic login
Let’s start by adding something very basic. To add some text to your application, you will need to type:
<Text>Login Page<Text>
Working with styles is very similar to CSS. If you wanted to add a style to the line of text that you just created, you would simply edit that line of text to:
<Text style={styles.mainheader}> My Login App</Text>
You can then add the text style under Stylesheet.create.
mainheader: {
color: ‘#000066’,
textAlign: ‘center’,
fontSize: 16
},
We are now going to create a fully functional login screen so that users can login, register for a new account, sign out and even reset their password. This is something you will see a lot in mobile apps, so it lays down a nice foundation for future projects.
04. Set up Firebase and NativeBase
We are going to start by installing three more libraries. The first is called Firebase, which is what we will use for our user authentication, and the second is called NativeBase, which is a UI component library. The last one is called React Native Dialog Input, which enables us to display a dialogue box where users can enter text. Navigate to your project folder using the command line and enter the below:
npm install firebase
npm install native-base
npm install --save react-native-dialog-input
Make sure you import Firebase, NativeBase and React Native Dialog Input at the top of the App.js file.
import * as firebase from ‘firebase’;
import { Container, Content, Header, Form, Input, Item,
Button, Label } from ‘native-base’
import DialogInput from ‘react-native-dialog-input’;
Next, we will need to setup the Firebase config just underneath the import commands. You will need to go and setup an account with Firebase to get your various settings. You can do this by registering at Firebase and creating a new project. Remember that you will need to enable email and password authentication from the dashboard.
var config = {
apiKey: “<API_KEY>”,
authDomain: “<PROJECT_ID>.firebaseapp.com”,
databaseURL: “https://<DATABASE_NAME>.firebaseio.
com”,
projectId: “<PROJECT_ID>”,
storageBucket: “<BUCKET>.appspot.com”,
messagingSenderId: “<SENDER_ID>”
};
firebase.initializeApp(config);
05. Build the container
The next step is to remove the <View> section underneath render(), which was automatically placed there by React upon creating the project, and replace it with the following container to setup the login form. The form will contain a label and an input field for both an email address and password. We will also create three buttons: one to login, one to sign up and the final button is for when a user wants to reset their password. We will set a margin at the top of each button to 10 pixels and set the font colour to white.
<Container style={styles.container}>
<Text style={styles.mainheader}>Login Page</Text>
<Form>
<Item>
<Label>Email</Label>
<Input
autocorrect={false}>
</Item>
<Item>
<Label>Password</Label>
<Input
secureTextEntry={true}>
</Item>
<Button style={{marginTop:10}} primary full
rounded>
<Text style={{color: ‘white’}}>Login</Text>
</Button>
<Button style={{marginTop:10}} success full
rounded>
<Text style={{color: ‘white’}}>Sign Up</Text>
</Button>
<Button style={{marginTop:10}} warning full
rounded>
<Text style={{color: ‘white’}}>Forgot Password</
Text>
</Button>
</Form>
</Container>
06. Set up the events
Firstly, we need to set up a constructor to set up the default state. The email and password default values will be set to empty. We will also set the value of isDialogVisible to false: this is going to be used for our password reset dialog box later on.
constructor(props) {
super(props)
this.state=({
email: ‘’,
password: ‘’,
isDialogVisible: false
})
}
We will now add onChangeText events to both of our text inputs, so that every time the user types something into the email or password fields, it will update the state of both email and password to that value.
onChangeText={(email) => this.setState({ email })}
onChangeText={(password) => this.setState({ password })}
We also need to add onPress functions to our login, sign-up and forgotten password buttons. Each one will call a different function. The login button will call a function called loginUser, the sign-up button will call signUpUser and the forgotten password button will call forgotPassword.
onPress={() => this.loginUser(this.state.email, this.state.
password)}’
onPress={() => this.signUpUser(this.state.email, this.state.
password)}
onPress={() => this.forgotPassword()}
07. Make sign-up function
It’s now time to begin building out our functions. We will begin with the sign-up function (signUpUser), which will attempt to create a new user inside Firebase; if it succeeds, then we will display an onscreen alert to inform the user that their account has been set up. However, if the user chooses a password that is less six characters in length, it will prompt them to enter something that is a minimum of six characters long. Finally, we need to add the catch error handler, so that if the sign-up attempt fails through Firebase, we will print the error message to the console.
signUpUser = (email, password) => {
try {
if(this.state.password.length<6)
{
alert(“Please enter at least 6 characters”)
return;
}
firebase.auth().createUserWithEmailAndPassword(ema
il, password)
alert(“Congratulations, your account has been setup”)
}
catch(error){
console.log(error.toString())
}
}
07. Add login function
Next, we will add the login (loginUser) function. This will try to log in the user with their email and password. If the user successfully signs in, it will display an alert to say that sign-in was successful, along with a sign out button. Once again, we will need to make sure we add a catch error handler in case there is an error with the login attempt.
loginUser = (email, password) => {
try {
firebase.auth().signInWithEmailAndPassword(email,
password).then((user) =>{
Alert.alert(
‘Signed In’,
‘You have signed in. Well done!’,
[
{text: ‘Sign Out’, onPress: this.signOutUser},
],
{ cancelable: false }
)
})
}
catch(error) {
console.log(error.toString())
}
}
08. Add sign out function
It’s now on to the sign-out function, which ensures that the user is signed out once they click the sign out button on the alert.
signOutUser = () => {
firebase.auth().signOut().then(function (user){
}).catch(function(error) {
console.log(error)
});
}
09. Create forgot password function
To finish off our project, we are going to build out a function that will enable the user to easily reset their password in case they’ve either forgotten it or want to change it for some other reason. First, we need to create the dialog box just outside of our <form> tags.
<DialogInput isDialogVisible={this.state.
isDialogVisible}
title={“Forgot Password”}
message={“Please input your email address”}
hintInput ={“john@test.com”}
submitInput={ (useremail) => {this.
sendReset(useremail)} }
closeDialog={ () => { this.setState({
isDialogVisible: this.state.isDialogVisible = false
})}}>
</DialogInput>
We now need to make the dialog box appear, so we will create the forgotPassword function, which will change the state of isDialogVisible to true.
forgotPassword = () => {
this.setState({
isDialogVisible: this.state.isDialogVisible = true
})
}
The dialog box will prompt the user to enter their email address. If the user clicks the cancel button, then the box will close, as it changes the state of the isDialogVisible back to false. If the user clicks the submit button then it will call a function called sendReset along with the email address.
Inside our sendReset, we will use the email address to create the Firebase sendPasswordResetEmail request.
sendReset = (useremail) => {
var auth = firebase.auth();
auth.sendPasswordResetEmail(useremail).then(function()
{
alert(“Password reset email has been sent”)
}).catch(function(error) {
console.log(error)
});
}
This article was originally published in issue 312 of net magazine. Buy issue 312 or subscribe here.
Related articles:
Thank you for reading 5 articles this month* Join now for unlimited access
Enjoy your first month for just £1 / $1 / €1
*Read 5 free articles per month without a subscription
Join now for unlimited access
Try first month for just £1 / $1 / €1