React Native

User Registration for React Native

Introduction

At the core of many apps, user accounts have a notion that lets users securely access their information. Parse provides a specialized user class called Parse.User that automatically handles much of the functionality required for user account management.

In this guide, you’ll learn how Parse.User class works by creating a user registration feature for your React Native App using Parse JS SDK.

Prerequisites

To complete this tutorial, you will need:

Goal

To build a User Registration feature using Parse for a React Native App.

Step 1 - Understanding the SignUp method

Parse User management uses the Parse.User object type, which extends the default ParseObject type while containing unique helper methods, such as current and getUsername, that will help you retrieve user data throughout your app. You can read more about the Parse.User object here at the official documentation.

In this guide, you will learn how to use the signUp method that creates a new valid and unique Parse.User object both locally and on the server, taking as arguments valid username and password values.

Step 2 - Create the user registration component

Let’s now build the functional component, which will call the signUp method in our App. First, create a new file in your root directory called UserRegistration.js (UserRegistration.tsx if you are using TypeScript) and also add the needed input elements (username and password inputs), using state hooks via useState to manage their data:

UserRegistration.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import React, { FC, ReactElement, useState } from "react";
import { Button, StyleSheet, TextInput } from "react-native";
import Parse from "parse/react-native";

export const UserRegistration = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  return (
    <>
      <TextInput
        style={styles.input}
        value={username}
        placeholder={"Username"}
        onChangeText={(text) => setUsername(text)}
        autoCapitalize={"none"}
      />
      <TextInput
        style={styles.input}
        value={password}
        placeholder={"Password"}
        secureTextEntry
        onChangeText={(text) => setPassword(text)}
      />
      <Button title={"Sign Up"} onPress={() => {}} />
    </>
  );
};

const styles = StyleSheet.create({
  input: {
    height: 40,
    marginBottom: 10,
    backgroundColor: '#fff',
  },
});

UserRegistration.tsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import React, { FC, ReactElement, useState } from "react";
import { Button, StyleSheet, TextInput } from "react-native";
import Parse from "parse/react-native";

export const UserRegistration: FC<{}> = ({}): ReactElement => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  return (
    <>
      <TextInput
        style={styles.input}
        value={username}
        placeholder={"Username"}
        onChangeText={(text) => setUsername(text)}
        autoCapitalize={"none"}
      />
      <TextInput
        style={styles.input}
        value={password}
        placeholder={"Password"}
        secureTextEntry
        onChangeText={(text) => setPassword(text)}
      />
      <Button title={"Sign Up"} onPress={() => {}} />
    </>
  );
};

const styles = StyleSheet.create({
  input: {
    height: 40,
    marginBottom: 10,
    backgroundColor: '#fff',
  },
});

Step 3 - Create a Sign Up function

You can now create the sign-up function that will call the signUp method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const doUserRegistration = async function () {
  // Note that this values come from state variables that we've declared before
  const usernameValue = username;
  const passwordValue = password;
  // Since the signUp method returns a Promise, we need to call it using await
  return await Parse.User.signUp(usernameValue, passwordValue)
    .then((createdUser) => {
      // Parse.User.signUp returns the already created ParseUser object if successful
      Alert.alert(
        'Success!',
        `User ${createdUser.getUsername()} was successfully created!`,
      );
      return true;
    })
    .catch((error) => {
      // signUp can fail if any parameter is blank or failed an uniqueness check on the server
      Alert.alert('Error!', error.message);
      return false;
    });
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const doUserRegistration = async function (): Promise<boolean> {
  // Note that this values come from state variables that we've declared before
  const usernameValue: string = username;
  const passwordValue: string = password;
  // Since the signUp method returns a Promise, we need to call it using await
  return await Parse.User.signUp(usernameValue, passwordValue)
    .then((createdUser: Parse.User) => {
      // Parse.User.signUp returns the already created ParseUser object if successful
      Alert.alert(
        'Success!',
        `User ${createdUser.getUsername()} was successfully created!`,
      );
      return true;
    })
    .catch((error: object) => {
      // signUp can fail if any parameter is blank or failed an uniqueness check on the server
      Alert.alert('Error!', error.message);
      return false;
    });
};

Note: Creating a new user using signUp also makes it the currently logged-in user, so there is no need for your user to log in again to continue using your App.

Insert this function inside the UserRegistration component, just before the return call, to be called and tested. Remember to update the form’s sign up button onPress action to () => doUserRegistration() and to import Alert from react-native. Your component should now look like this:

UserRegistration.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import React, { FC, ReactElement, useState } from "react";
import { Alert, Button, StyleSheet, TextInput } from "react-native";
import Parse from "parse/react-native";

export const UserRegistration = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  const doUserRegistration = async function () {
    // Note that this values come from state variables that we've declared before
    const usernameValue = username;
    const passwordValue = password;
    // Since the signUp method returns a Promise, we need to call it using await
    return await Parse.User.signUp(usernameValue, passwordValue)
      .then((createdUser) => {
        // Parse.User.signUp returns the already created ParseUser object if successful
        Alert.alert(
          "Success!",
          `User ${createdUser.get("username")} was successfully created!`
        );
        return true;
      })
      .catch((error) => {
        // signUp can fail if any parameter is blank or failed an uniqueness check on the server
        Alert.alert("Error!", error.message);
        return false;
      });
  };

  return (
    <>
      <TextInput
        style={styles.input}
        value={username}
        placeholder={"Username"}
        onChangeText={(text) => setUsername(text)}
        autoCapitalize={"none"}
      />
      <TextInput
        style={styles.input}
        value={password}
        placeholder={"Password"}
        secureTextEntry
        onChangeText={(text) => setPassword(text)}
      />
      <Button title={"Sign Up"} onPress={() => doUserRegistration()} />
    </>
  );
};

const styles = StyleSheet.create({
  input: {
    height: 40,
    marginBottom: 10,
    backgroundColor: "#fff",
  },
});

UserRegistration.tsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import React, { FC, ReactElement, useState } from "react";
import { Alert, Button, StyleSheet, TextInput } from "react-native";
import Parse from "parse/react-native";

export const UserRegistration: FC<{}> = ({}): ReactElement => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  const doUserRegistration = async function (): Promise<boolean> {
    // Note that this values come from state variables that we've declared before
    const usernameValue: string = username;
    const passwordValue: string = password;
    // Since the signUp method returns a Promise, we need to call it using await
    return await Parse.User.signUp(usernameValue, passwordValue)
      .then((createdUser: Parse.User) => {
        // Parse.User.signUp returns the already created ParseUser object if successful
        Alert.alert(
          "Success!",
          `User ${createdUser.get("username")} was successfully created!`
        );
        return true;
      })
      .catch((error: object) => {
        // signUp can fail if any parameter is blank or failed an uniqueness check on the server
        Alert.alert("Error!", error.message);
        return false;
      });
  };

  return (
    <>
      <TextInput
        style={styles.input}
        value={username}
        placeholder={"Username"}
        onChangeText={(text) => setUsername(text)}
        autoCapitalize={"none"}
      />
      <TextInput
        style={styles.input}
        value={password}
        placeholder={"Password"}
        secureTextEntry
        onChangeText={(text) => setPassword(text)}
      />
      <Button title={"Sign Up"} onPress={() => doUserRegistration()} />
    </>
  );
};

const styles = StyleSheet.create({
  input: {
    height: 40,
    marginBottom: 10,
    backgroundColor: "#fff",
  },
});

Step 4 - Testing the component

The final step is to use our new component inside your React Native Application App.js file (or App.tsx if using TypeScript):

App.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
return (
  <>
    <StatusBar />
    <SafeAreaView style={styles.container}>
      <>
        <Text style={styles.title}>React Native on Back4App</Text>
        <Text>User registration tutorial</Text>
        <UserRegistration />
      </>
    </SafeAreaView>
  </>
);

// Remember to add some styles at the end of your file
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  title: {
    fontSize: 20,
    fontWeight: "bold",
  },
});

App.tsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
return (
  <>
    <StatusBar />
    <SafeAreaView style={styles.container}>
      <>
        <Text style={styles.title}>React Native on Back4App</Text>
        <Text>User registration tutorial</Text>
        <UserRegistration />
      </>
    </SafeAreaView>
  </>
);

// Remember to add some styles at the end of your file
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  title: {
    fontSize: 20,
    fontWeight: "bold",
  },
});

Your app now should look like this:

React Native Back4App

After providing the desired user credentials, you will see this message after pressing on Sign Up if everything was successful:

React Native Save Data Confirmation

Error handling can be tested if you try to register a user with the same username as before:

React Native Save Data Confirmation

You will get another error if you try to sign up with no password:

React Native Save Data Confirmation

Conclusion

At the end of this guide, you learned how to register new Parse users on React Native. In the next guide, we will show you how to log in and out users.