Creating "Quarantine Pro" — A Fun Learning Experiment in React Native

Published on May 14, 2020

15 min read

EXPO

Covid-19 changed our way of life since the start of 2020 - a year some of us want to fast forward like a button on that TV remote. That said, self-isolating is the best thing you can do right now, and thus, isolating ourselves at Jscrambler, we came up with a fun, simple React Native app idea.

The app is all about how long you have been quarantining. As a user, you input the date when you started isolating and the app is going to display a fun message to tell you how far you have come in the quarantine “game”.

That said, apart from being fun, this tutorial is going to show you how to use the Expo's SDK version 37.x.x. of Expo to build a demo app. You will learn:

  • How to use Expo font hook;
  • How to use a date time picker modal to select a date;
  • Use Moment.js to convert the data input provided by the user and calculate the difference between the current date.

Here is a sneak peek of what we intend to build in this tutorial:

js16

You can find the complete code for this tutorial at this GitHub repo.

Create a New Expo App

🔗

Start by creating a new Expo app at your favorite side-projects location in your local development environment. Run the following command from a new terminal window to generate a new React Native app using expo-cli.

npx expo-cli init DaVinciOfIsolation

When asked to select a template, choose the template blank from Managed workflow.

js1

After that, press enter and let expo-cli install the dependencies required to start this project.

Once the project has initialized generating, go to the project directory from the terminal window and start the Expo bundler service.

expo start

This will start the Expo app in a simulator or device of your choice where the Expo client is installed. For more information on how to install an Expo client, please visit the official documentation.

Once the app is running in the Expo client, you are going to be welcomed by the following default screen:

js2

Let us install the npm dependencies we are going to need to build this project by executing the following command:

expo install expo-font @use-expo/font @react-native-community/datetimepicker

The expo install adds dependencies using a specific version that is compatible with the Expo SDK.

Also, install the following npm packages either using npm install or using yarn:

yarn add react-native-modal-datetime-picker moment

With that, we have installed the required set of npm dependencies. Let us move further and start building the app.

How To Use Custom Fonts In An Expo App

🔗

Install a New Font

🔗

In this app, we are going to use a specific custom font that is free to download from Google Fonts - Press Start 2P. It is available to download here.

js3

To use this font or any other custom font, create a new directory called fonts inside the assets/ folder. Then place the font file(s) you have just downloaded. The path to the fonts directory ./assets/fonts is a convention that Expo developers recommend using when placing custom fonts in your app.

After placing the file inside the newly created directory, the file structure will look like below.

js4

When you are downloading a font to use in an Expo React Native app, make sure you download either a font in either .otf or .ttf format. Those are the two formats that work across all Expo platforms such as web, iOS, and Android.

Use The useFonts Hook

🔗

To use any hook in a React or React Native app, you have to use functional components. To set up a new font, start by importing the following statements.

1import React from 'react';
2import { View, Text } from 'react-native';
3import { useFonts } from '@use-expo/font';
4import { AppLoading } from 'expo';

The useFonts hook takes one argument as a JavaScript object and returns a single item list containing a value telling you whether the font is loaded or not. This eliminates the need for a lot of boilerplate code to make this check.

After you have imported the statements, create a new object called customFont. It will have a key - the name of the font itself - and the value of this key - the path to the font file in assets/fonts/ directory.

1const customFont = {
2 'Press-Start2p': require('./assets/fonts/PressStart2P-Regular.ttf')
3};

Next, inside the function component, define the isLoaded variable from the useFonts hook and pass the customFont object as its argument.

Also, when the font is in the loading state or has not loaded yet, it is a good practice to make use of the AppLoading component from Expo and render nothing on the screen. Once the font has loaded, the screen will display the content of the functional component.

Here is the complete code of the App component. Right now, we are displaying the title of the app using the new font we have just installed.

1export default function App() {
2 const [isLoaded] = useFonts(customFont);
3
4 if (!isLoaded) {
5 return <AppLoading />;
6 }
7
8 return (
9 <View
10 style={{
11 flex: 1,
12 alignItems: 'center',
13 backgroundColor: '#ffbd12'
14 }}
15 >
16 <Text
17 style={{
18 fontFamily: 'Press-Start2p',
19 fontSize: 24,
20 marginTop: 80,
21 paddingHorizontal: 20
22 }}
23 >
24 {`Are You a Quarantine Pro?`}
25 </Text>
26 </View>
27 );
28}

From the above snippet, make sure you describe the fontFamily property on the Text component. This is the only way the font is going to be used for a specific text component.

Go back to the Expo client and you are going to see the following result.

js5

That's it! You have completed the first step of loading fonts and using them in a React Native app. Thanks to Cedric van Putten who has made the process of loading and mapping fonts easier for us. For more information check out Cedric's collection of hooks that you can use in an Expo app here.

Create a Button To Use The Datetime Picker Modal

🔗

Since we have already installed the required npm dependencies to show a date picker modal (that uses the native date picker module), let us add a button to the current App.js file in order to display this modal.

Start by modifying the import statements as stated below and add the new ones.

1import React, { useState } from 'react';
2import {
3 View,
4 Text,
5 StyleSheet,
6 Dimensions,
7 TouchableWithoutFeedback
8} from 'react-native';
9import {
10 Fontisto,
11 MaterialCommunityIcons,
12 FontAwesome
13} from '@expo/vector-icons';
14import DateTimePickerModal from 'react-native-modal-datetime-picker';

To set the width and the height of the button, we are going to use the Dimensions API from the react-native core. The width and height of the button are going to be calculated based on the width of the current window.

Define a variable W that is going to represent the width of the window before the App functional component.

1const W = Dimensions.get('window').width;

Next, after the app's title text, define another container View component for the button. We are going to wrap the contents of the TouchableWithoutFeedback button inside a separate View component since this touchable component from React Native is only allowed to have a child component. However, we are going to have two child components: the icon of the button and the text. Modify the return statement of the App component as per the code snippet below.

1return (
2 <View style={styles.container}>
3 <Text style={styles.title}>{`Are You a Quarantine Pro?`}</Text>
4 <TouchableWithoutFeedback>
5 <View style={styles.pickerContainer}>
6 <Fontisto style={styles.icon} name="calendar" size={48} />
7 <Text style={styles.pickerText}>{`Tap here to\nselect a date`}</Text>
8 </View>
9 </TouchableWithoutFeedback>
10 </View>
11);

Add the following styles for the above code snippet. Let's make use of the StyleSheet object to manage styles in the current component file.

1const styles = StyleSheet.create({
2 container: {
3 flex: 1,
4 alignItems: 'center',
5 backgroundColor: '#ffbd12'
6 },
7 title: {
8 fontFamily: 'Press-Start2p',
9 fontSize: 24,
10 marginTop: 80,
11 paddingHorizontal: 20,
12 lineHeight: 30
13 },
14 pickerContainer: {
15 marginTop: 20,
16 backgroundColor: '#00c6ae',
17 width: W / 1.2,
18 height: W / 4,
19 borderRadius: 10,
20 borderWidth: 1,
21 borderColor: '#000',
22 borderBottomWidth: 5,
23 borderBottomColor: '#000',
24 justifyContent: 'center',
25 alignItems: 'center',
26 flexDirection: 'row'
27 },
28 pickerText: {
29 fontFamily: 'Press-Start2p',
30 fontSize: 14,
31 paddingHorizontal: 10,
32 lineHeight: 20
33 },
34 icon: {
35 color: '#000'
36 }
37});

Refresh the Expo client to get the following result.

js6

Now, let us bind the date picker modal to this button. We already imported the npm package react-native-modal-datetime-picker we need for this step. Why are we using this library over the default @react-community/react-native-datetimepicker because this special library exposes a cross-platform interface for showing the native date-picker and time-picker inside a modal.

For our app, we are also going to evaluate the number of days the user has already spent in quarantine based on the date they choose as the input. Let us define a few state variables using the useState hook from React for the following reasons:

  • pickedDate to store the date picked by the user;
  • isDatePickerVisible to show or hide the date picker modal.

We have to define three helper functions along with these state variables. The first two will handle the visibility of the date picker modal. The third one will handle the confirm button from the date picker modal - as to what action to take when the user has to choose a date. The action we have to take here is to hide the date picker modal as well as store the value of the date in the state variable pickedDate.

1export default function App() {
2 // ... rest of the component remains same
3
4 const [pickedDate, setPickedDate] = useState(null);
5 const [isDatePickerVisible, setDatePickerVisibility] = useState(false);
6
7 function showDatePicker() {
8 setDatePickerVisibility(true);
9 }
10
11 function hideDatePicker() {
12 setDatePickerVisibility(false);
13 }
14
15 function handleConfirm(date) {
16 console.log('A date has been picked: ', date);
17 hideDatePicker();
18 setPickedDate(date);
19 }
20
21 return (
22 <View style={styles.container}>
23 <Text style={styles.title}>{`Are You a Quarantine Pro?`}</Text>
24 <TouchableWithoutFeedback onPress={showDatePicker}>
25 <View style={styles.pickerContainer}>
26 <Fontisto style={styles.icon} name="calendar" size={48} />
27 <Text style={styles.pickerText}>{`Tap here to\nselect a date`}</Text>
28 </View>
29 </TouchableWithoutFeedback>
30 <DateTimePickerModal
31 isVisible={isDatePickerVisible}
32 mode="date"
33 onConfirm={handleConfirm}
34 onCancel={hideDatePicker}
35 headerTextIOS="When did you start isolating?"
36 />
37 </View>
38}

The showDatePicker method is going to be triggered every time a user taps the button to display the picker modal. The component will only render on the device's screen when this method triggers.

js7

When the user taps anywhere outside the modal or taps on the Cancel button, the modal is hidden again and nothing happens.

js8

js9

However, when a date is selected and the user taps Confirm, further actions can be taken. For now, let us show the date picked by the user in a console statement.

The output is shown in the Expo server that is running in the terminal window.

js11

This means that the user input is now stored in the state variable pickedDate.

Also, you can apply other props available in @react-community/react-native-datetimepicker. In the date picker modal we are implementing, there is small customization using the prop headerTextIOS. This prop allows changing the title of the picker modal for iOS devices.

Evaluate The “Quarantine Score”

🔗

The second missing piece of the puzzle in our current app is to have a button to calculate the day(s) difference between the user's input and the current date (we will use this as our “quarantine score”).

We are going to follow the same strategy design-wise as in the previous section. Display a button that users can tap to see their score.

Start by importing the moment library in the App.js file after the rest of the import statements. It is going to handle the calculation between the user's input and the current date.

1// rest of the import statements
2import moment from 'moment';

This library is also going to help us format the input from the date picker modal and display only the date (and not time) from the user's input in the format YYYY-MM-DD.

Modify the return statement by adding a new View container that consists of a text message and the button to calculate the difference between the days.

Also, before modifying the return statement of the functional component, add a helper method called daysRemaining() that is going to calculate the difference. We are going to store this difference in a state variable called days. This state variable is going to be used in the next section to display the correct result on the screen.

The difference is going to be calculated between the pickedDate (which is the user's input) and the todaysDate (which is the current date).

1export default function App() {
2const [days, setDays] = useState('');
3
4function daysRemaining() {
5 // user's input
6 let eventdate = moment(pickedDate);
7 // getting current date
8 let todaysdate = moment();
9 let remainingDays = todaysdate.diff(eventdate, 'days');
10 setDays(remainingDays);
11 return remainingDays;
12 }
13
14 return (
15 <View style={styles.container}>
16 <Text style={styles.title}>{`Are You a Quarantine Pro?`}</Text>
17 <TouchableWithoutFeedback onPress={showDatePicker}>
18 <View style={styles.pickerContainer}>
19 <Fontisto style={styles.icon} name="calendar" size={48} />
20 <Text style={styles.pickerText}>{`Tap here to\nselect a date`}</Text>
21 </View>
22 </TouchableWithoutFeedback>
23 <DateTimePickerModal
24 isVisible={isDatePickerVisible}
25 mode="date"
26 onConfirm={handleConfirm}
27 onCancel={hideDatePicker}
28 headerTextIOS="When did you start isolating?"
29 />
30 {/* ADD BELOW */}
31 <View style={styles.showDateContainer}>
32 <Text style={styles.showDateText}>
33 You started isolating on{' '}
34 {pickedDate && (
35 <Text style={styles.showDateText}>
36 {moment(pickedDate).format('YYYY-MM-DD')}.
37 </Text>
38 )}
39 </Text>
40 <TouchableWithoutFeedback onPress={daysRemaining}>
41 <View style={styles.evaluateButtonContainer}>
42 <Text style={styles.evaluateButtonText}>Check your level</Text>
43 </View>
44 </TouchableWithoutFeedback>
45 </View>
46 </View>
47}

The picked date is displayed in the desired format using moment().format() functions. The pickedDate will only show once the user has provided input by selecting the date from the date picker modal.

Here are the corresponding styles for the above snippet.

1const styles = StyleSheet.create({
2 // rest of the styles remain same
3 showDateContainer: {
4 marginTop: 20,
5 backgroundColor: '#F95A2C',
6 width: W / 1.2,
7 height: W / 2,
8 borderRadius: 10,
9 borderWidth: 1,
10 borderColor: '#000',
11
12 alignItems: 'center'
13 },
14 showDateText: {
15 fontFamily: 'Press-Start2p',
16 fontSize: 14,
17 padding: 10,
18 marginTop: 20,
19 lineHeight: 20
20 },
21 evaluateButtonContainer: {
22 marginTop: 20,
23 backgroundColor: '#1947E5',
24 width: W / 1.4,
25 height: W / 6,
26 borderRadius: 10,
27 borderWidth: 1,
28 borderColor: '#000',
29 borderBottomWidth: 5,
30 borderBottomColor: '#000',
31 justifyContent: 'center',
32 alignItems: 'center',
33 flexDirection: 'row'
34 },
35 evaluateButtonText: {
36 color: '#fff',
37 fontFamily: 'Press-Start2p',
38 fontSize: 14,
39 paddingHorizontal: 10,
40 lineHeight: 20
41 },
42}

Here is the initial result you are going to get in the Expo client.

js13

Select the date from the picker modal. After the date has been picked, it will be shown as below.

js14

Rendering The “Quarantine Level”

🔗

The last piece of this current app is to display the result when the user presses the button that says Check your level.

js15

Modify the return statement of the App component. When the result is available, we are going to show the user's quarantine level - but, when it’s not available, this UI box will display a default message. Just after the previous section's snippet, add another View container component.

When the evaluation is done, renderAchievements() is going to return only the icon and the text message that is based on the score (difference between the current date and the user's input date). Since we are using a state variable called days to store this difference, it becomes easy to conditionally render the message.

1export default function App() {
2// rest of the code remains the same
3
4function renderAchievements() {
5 if (days > 1 && days < 5) {
6 return (
7 <>
8 <MaterialCommunityIcons
9 name="guy-fawkes-mask"
10 color="#000"
11 size={54}
12 />
13 <Text style={styles.resultText}>
14 Quarantine Noob. Don't forget to wear a mask. Keep self-isolating.
15 </Text>
16 </>
17 );
18 } else if (days >= 5 && days <= 7) {
19 return (
20 <>
21 <MaterialCommunityIcons name="glass-wine" color="#000" size={54} />
22 <Text style={styles.resultText}>Quarantine Connoisseur. Welcome to the (literal) dark side!</Text>
23 </>
24 );
25 } else if (days >= 8 && days <= 15) {
26 return (
27 <>
28 <MaterialCommunityIcons
29 name="seat-legroom-reduced"
30 color="#000"
31 size={54}
32 />
33 <Text style={styles.resultText}>Quarantine Proficient. AKA “What is pants?</Text>
34 </>
35 );
36 } else if (days >= 16 && days <= 22) {
37 return (
38 <>
39 <MaterialCommunityIcons
40 name="star-circle-outline"
41 color="#000"
42 size={54}
43 />
44 <Text style={styles.resultText}>Quarantine Veteran. #StayHome became your life motto.</Text>
45 </>
46 );
47 } else if (days >= 23) {
48 return (
49 <>
50 <FontAwesome name="paint-brush" color="#000" size={54} />
51 <Text style={styles.resultText}>THE ULTIMATE QUARANTINE PRO! You are part of the solution - thank you!</Text>
52 </>
53 );
54 } else
55 return (
56 <Text style={styles.resultText}>Your level will be shown here.</Text>
57 );
58 }
59
60 return (
61 <View style={styles.container}>
62 <Text style={styles.title}>{`Are You a Quarantine Pro?`}</Text>
63 <TouchableWithoutFeedback onPress={showDatePicker}>
64 <View style={styles.pickerContainer}>
65 <Fontisto style={styles.icon} name="calendar" size={48} />
66 <Text style={styles.pickerText}>{`Tap here to\nselect a date`}</Text>
67 </View>
68 </TouchableWithoutFeedback>
69 <DateTimePickerModal
70 isVisible={isDatePickerVisible}
71 mode="date"
72 onConfirm={handleConfirm}
73 onCancel={hideDatePicker}
74 headerTextIOS="When did you start isolating?"
75 />
76 <View style={styles.showDateContainer}>
77 <Text style={styles.showDateText}>
78 You started isolating on{' '}
79 {pickedDate && (
80 <Text style={styles.showDateText}>
81 {moment(pickedDate).format('YYYY-MM-DD')}.
82 </Text>
83 )}
84 </Text>
85 <TouchableWithoutFeedback onPress={daysRemaining}>
86 <View style={styles.evaluateButtonContainer}>
87 <Text style={styles.evaluateButtonText}>Check your level</Text>
88 </View>
89 </TouchableWithoutFeedback>
90 </View>
91
92 {/* ADD BELOW */}
93
94 <View style={styles.resultContainer}>{renderAchievements()}</View>
95 </View>
96}

Here are styles for the renderAchievements().

1const styles = StyleSheet.create({
2 // rest of the styles remain same
3 resultContainer: {
4 marginTop: 20,
5 backgroundColor: '#FF89BB',
6 width: W / 1.2,
7 height: W / 2,
8 borderRadius: 10,
9 borderWidth: 1,
10 borderColor: '#000',
11 justifyContent: 'center',
12 alignItems: 'center'
13 },
14 resultText: {
15 color: '#fff',
16 fontFamily: 'Press-Start2p',
17 fontSize: 16,
18 padding: 15,
19 lineHeight: 20
20 }
21});

Now, go back to the Expo client and you will be welcomed by the following screen:

js16

Try to run the app and select different dates to see different results as shown below.

js17

Conclusion

🔗

We hope you had fun building this app and learning as well. The main objectives of this tutorial are complete now and summarized for better understanding as below.

Check out @react-native-community/datetimepicker for more information on how to customize the date picker modal or try to use a time picker. The Moment.js library is full of functions to help you manage date and time in JavaScript apps (another tutorial here).

The app is available at Expo here, you just need to scan the QR code with the Expo client (iOS | Android) app on your device.

Originally published at Jscrambler's blog.


More Posts

Browse all posts

Aman Mittal author

I'm a software developer and a technical writer. On this blog, I write about my learnings in software development and technical writing.

Currently, working maintaining docs at 𝝠 Expo. Read more about me on the About page.


Copyright ©  2019-2024 Aman Mittal · All Rights Reserved.