Thursday, 7 June, 2018 UTC


Summary

This is part three of a three-part series on getting started with React Native. It is recommended to read part one and part two before starting this section.In this part, you’ll learn how to use native device functionality in React Native. Specifically, you’ll be accessing the device’s camera and file system to implement the app’s progress page. Here’s what the final output will look like:
The full source code of the app is available on this Github repo. You can run the demo on your browser or on your Expo client app by scanning the QR code found on that page.
Prerequisites
As this is a beginner series, knowledge of the following are not required:
  • React Native
  • React
Knowledge of the following is required:
  • HTML
  • CSS
  • JavaScript – ES5 is required, while familiarity with ES6 features is helpful.
  • Git – cloning repos, switching branches.
The following versions are used in this tutorial:
  • Expo Client App version 2.4.7
  • Expo CLI version 53.0.0
  • Expo SDK version 26.0.0
  • React version 16.3.0-alpha.1
  • React Navigation version 1.5.9
  • React Simple Store version 1.3.0
If you’re reading this at a later time, and you have issues running the code, be sure to check out the following changelogs or release notes. Take note of any breaking changes or deprecations and update the code accordingly. I’ve linked to them above, in case you missed it.
Reading the first and second part of the series is not required if you already know the basics of styling and scripting in React Native. Go through the following steps if you want to follow along:
  1. Install Expo and the Expo client app for your iOS or Android device. The client app will be used for running the app.
  2. Clone the Github repo:
    git clone https://github.com/anchetaWern/increment.git
    cd increment
  1. Switch to the part2 branch:
    git checkout part2
  1. Install all the dependencies:
    npm install
What you’ll be building
In this part of the series, you’ll be implementing the progress page of the app. This page allows the user to take selfie pictures of their workout progress. The photos are stored in the device’s filesystem and are viewable from the app at a later time.
At this point, you should be fairly confident in working with React Native. That’s why I’ll point you to the documentation of the two Expo API’s that we’ll be using:
  • Camera
  • FileSystem
You can still follow along with the tutorial if you want. But if you want a bit of a challenge, I encourage you to read those docs and try to implement the features on your own.
Once you’ve decided which path to choose, navigate inside the increment folder and execute the following on the terminal:
    exp start
Scan the QR code like usual so you can start developing.
Updating the Progress page
I’d like to take a different approach in this tutorial. The usual approach that I take is a top-to-bottom approach where I talk about the code as it appears on the file. This time I’ll let the implementation guide the order of things. So expect to be working on multiple files and jump from one line of code to another.

Taking Photos

The first thing that needs to be implemented is the button for opening the camera. Update it so the navigationOptions becomes a function which returns the navigation options. This way we can access the navigation params. We need it because just like in the Log Workout page, there’s a need to call a function which modifies the state. We can’t really call a function from inside the component class so we pass it as a navigation parameter instead:
    // app/screens/Progress.js
    static navigationOptions = ({ navigation }) => {
      const { params } = navigation.state;

      return {
        headerTitle: 'Progress',
        headerRight: (
          <IconButton size={25} color="#FFF" onPress={() => {
            params.openCamera();
          }} />
        ),
        headerStyle: {
          backgroundColor: '#333'
        },
        headerTitleStyle: {
          color: '#FFF'
        }
      }
    };
Inside the Progress class, create the openCamera function. This will update the state to make the camera visible:
    openCamera = () => {
      this.setState({
        is_camera_visible: true
      });
    }
Don’t forget to initialize it on the state so the camera isn’t shown by default:
    state = {
        is_camera_visible: false,
    }
Add the navigation param once the component is mounted:
    componentDidMount() {
      this.props.navigation.setParams({
        'openCamera': this.openCamera
      });
    }
The next step is to ask for permission to use the device’s camera. An app cannot simply use native device functionality without asking permission from the user first. Expo comes with the Permissions API for tasks like these. Import it near the top of the file along with the Camera:
    import { Permissions, Camera } from 'expo';
The best time to ask for permission is the time before the Progress page is rendered on the screen. The code below asks for permission to use the camera. If the user grants the request, the state has_camera_permission is updated to true:
    componentWillMount() {
      Permissions.askAsync(Permissions.CAMERA).then((response) => {
        this.setState({
          has_camera_permission: response.status === 'granted'
        });
      });
    }
The next step is to render the camera UI. We don’t really need to create a separate page for it so we’ll just use a modal:
    render() {
      return (
        <View style={styles.wrapper}>
          <Modal
            animationType="slide"
            transparent={false}
            visible={this.state.is_camera_visible}
            onRequestClose={() => {
              this.setState({
                is_camera_visible: false
              });
            }}>
            <View style={styles.modal}>
              {/* next: add code for rendering camera */}
            </View>
          </Modal>
        </View>  
      );
    }
Use the Camera component from Expo to render a camera UI inside the app:
    {
      this.state.has_camera_permission &&
      <Camera style={styles.wrapper} type={this.state.type} ref={ref => { this.camera = ref; }}>
        <View style={styles.camera_body}>
          <View style={styles.upper_buttons_container}>
            <IconButton is_transparent={true} icon="close"
              styles={[styles.camera_button, styles.camera_close_button]}
              onPress={this.closeCamera} />

            <IconButton is_transparent={true} icon="flip"
              styles={[styles.camera_button, styles.camera_flip_button]}
              onPress={this.flipCamera} />
          </View>

          <View style={styles.lower_buttons_container}>
            <IconButton is_transparent={true} icon="photo-camera"
              styles={styles.camera_photo_button}
              onPress={this.takePicture} />
          </View>
        </View>
      </Camera>
    }
In the code above, we have a few new things. First is this bit of code:
    ref={ref => { this.camera = ref; }}
This creates a reference to the Camera component. Coming from the HTML world, it’s like assigning an ID to the component so you can refer to it later. In this case, the reference to the component is assigned to this.camera. We can then use it to perform actions using the camera.
Next, is the type prop passed to the Camera. This allows us to specify the camera type. There can only be two possibilities for this: front or back. front is used when taking a selfie. While for every thing else it’s back. We’re storing this information in the state so we can easily flip between front and back cameras:
    type={this.state.type}
Next is the is_transparent prop passed to the IconButton. :
    is_transparent={true}
We’re using this to decide whether to use the regular icon button or a transparent one. We need the transparent for the camera’s buttons because we don’t want any background surrounding the actual button.
To implement the transparent button, open the app/components/IconButton.js file and include the TouchableOpacity component:
    import { TouchableHighlight, TouchableOpacity } from 'react-native';
If the is_transparent prop is passed, use TouchableOpacity instead:
    if(props.is_transparent){
      return (
        <TouchableOpacity style={[styles.transparent_icon_button, props.styles]} onPress={props.onPress}>
          <MaterialIcons name={icon_name} size={icon_size} color={color} />
        </TouchableOpacity>
      );
    }
In the code above, we’re using two separate style declarations for the transparent button (as indicated by the array syntax). One relies on a pre-declared style, and the other relies on a prop.
Update the styles for the component:
    // app/components/IconButton/styles.js
    transparent_icon_button: {
      alignItems: 'center',
    }
Going back to the app/screens/Progress.js file, the IconButton should now be usable as a transparent button.
At the top of the file, don’t forget to include Modal from react-native:
    // app/screens/Progress.js
    import { /*previously added packages here*/ Modal } from 'react-native';
Next, add the styles to the components that we just used:
    wrapper: {
      flex: 1
    },
    modal: {
      marginTop: 22,
      flex: 1
    },
    camera_body: {
      flex: 1,
      backgroundColor: 'transparent',
      flexDirection: 'column'
    },
    upper_buttons_container: {
      flex: 1,
      alignSelf: 'stretch',
      flexDirection: 'row',
      justifyContent: 'space-between'
    },
    lower_buttons_container: {
      flex: 1,
      alignSelf: 'stretch',
      justifyContent: 'flex-end'
    },
    camera_button: {
      padding: 10
    },
    camera_close_button: {
      alignSelf: 'flex-start',
      alignItems: 'flex-start'
    },
    camera_flip_button: {
      alignSelf: 'flex-start',
      alignItems: 'flex-end'
    },
    camera_photo_button: {
      alignSelf: 'center',
      alignItems: 'center',
      paddingBottom: 10
    },
Next, we need to implement the three functions that the camera buttons uses:
  • closeCamera – used for closing the camera modal.
  • flipCamera – used for flipping the camera (front or back).
  • takePicture – used for capturing a photo.
I’ll leave it to you to implement the first function.
As for the flipCamera, it will update the type in the state based on its current value. So if it’s currently using the back camera, then it changes it to the front and vice-versa:
    flipCamera = () => {
      this.setState({
        type: this.state.type === Camera.Constants.Type.back
          ? Camera.Constants.Type.front
          : Camera.Constants.Type.back,
      });
    }
Next is the takePicture function. It uses the Camera reference we’ve created earlier to call the takePictureAsync method. This method captures a picture and saves it to the app’s cache directory:
    takePicture = () => {
      if(this.camera){ // check whether there's a camera reference
        this.camera.takePictureAsync().then((data) => {
          // next: add code for processing the response data from the camera
        });
      }

    }
The next step is to move the photo to a permanent directory. But before that, we first have to generate a filename to be used for the photo. To make it unique, we’ll just stick with the current date and time:
    let datetime = getPathSafeDatetime(); // use a file path friendly datetime
Here’s the getPathSafeDatetime() function. All it does is format the current date and time to one that is safe for use as a filename. So 4/20/2018, 9:38:12 PM becomes 4-20-2018+9_38_51+PM:
    // app/lib/general.js
    function getPathSafeDatetime() {
      let datetime = getLocalDateTime(new Date()).replace(/\//g, '-').replace(',', '').replace(/:/g, '_').replace(/ /g, '+');
      return datetime;
    }
Don’t forget to import it:
    // app/screens/Progress.js
    import { getPathSafeDatetime } from '../lib/general';
The only problem left is how to determine the full path in which the file will be saved. Remember that we can’t simply use a relative path like so:
    let file_path = `./${datetime}.jpg`;
This is because the relative path isn’t actually a directory where we can store files. Remember that the JavaScript files aren’t actually compiled when the app is generated. So the relative path is still the app/screens directory.
For us to get the full path, we need to use the FileSystem API from Expo:
    import { Permissions, Camera, FileSystem } from 'expo';
We’ll need to re-use the full path a few times so we declare it once inside the constructor along with the file name prefix:
    constructor(props) {
      super(props);
      this.document_dir = FileSystem.documentDirectory; // the full path to where the photos should be saved (includes the trailing slash)
      this.filename_prefix = 'increment_photo_'; // prefix all file names with this string
    }
Going back inside the response for taking pictures, we can now bring the full path and the file name together:
    this.camera.takePictureAsync().then((data) => {
      let datetime = getPathSafeDatetime();
      let file_path = `${this.document_dir}${this.filename_prefix}${datetime}.jpg`;
      // next: add code for moving the photo to its permanent location
    });
At this point, we can now move the photo to its permanent location:
    FileSystem.moveAsync({
      from: data.uri, // the path to where the photo is saved in the cache directory
      to: file_path 
    })
    .then((response) => {
      // next: add code for storing the file name and updating the state
    });
Next, construct the data to be saved in local storage. We need this for fetching the actual photos later:
    let photo_data = {
      key: uniqid(), // unique ID for the photo
      name: datetime // the photo's filename
    };
    store.push('progress_photos', photo_data); // save it on local storage
Also update the state so the picture that has just been taken will be rendered in the UI:
    let progress_photos = [...this.state.progress_photos];
    progress_photos.push(photo_data);

    this.setState({
      progress_photos: progress_photos
    });

    Alert.alert(
      'Saved',
      'Your photo was successfully saved!',
    );
Don’t forget to include the React Native Simple Store library and the components and functions we’ve used:
    import store from 'react-native-simple-store';
    import { /*other packages*/ Alert } from 'react-native';
    import { /*other functions*/ uniqid } from '../lib/general';

Rendering Photos

The last thing that needs to be implemented is the rendering of previously captured photos. To do that, we first have to fetch the names of the previously saved photos from local storage and update the state:
    componentDidMount() {
      /* previously added code: setting additional navigation params */
      store.get('progress_photos')
        .then((response) => {
          if(response){
            this.setState({
              progress_photos: response
            });
          }
        });
    }
Next, update the render method to show an alert box if there are no photos added yet. Otherwise, use the FlatList component to render the photos. Add the numColumns prop to specify how many numbers of columns you want to render for each row:
    render() {

      return (
        <View style={styles.wrapper}>
          /* previously added code: camera modal */
          {
            this.state.progress_photos.length == 0 &&
            <AlertBox text="You haven't taken any progress pictures yet." type="info" />
          }

          {
            this.state.progress_photos.length > 0 &&
            <FlatList data={this.state.progress_photos} numColumns={2} renderItem={this.renderItem} />
          }
        </View>
      );

    }
Don’t forget to include the AlertBox component at the top of the file:
    import AlertBox from '../components/AlertBox';
Next, update the renderItem function to use the data from the state. Also update the function for handling the onPress event:
    renderItem = ({item}) => {

      let name = friendlyDate(item.name);
      let photo_url = `${this.document_dir}${this.filename_prefix}${item.name}.jpg`;

      return (
        <TouchableHighlight key={item.key} style={styles.list_item} underlayColor="#ccc" onPress={() => {
          this.showPhoto(item);
        }}>
          <View style={styles.image_container}>
            <Image
              source={{uri: photo_url}}
              style={styles.image}
              ImageResizeMode={"contain"} />
            <Text style={styles.image_text}>{name}</Text>
          </View>
        </TouchableHighlight>
      );

    }
Update the app/lib/general.js file to include the friendlyDate function. All this function does is format the file path friendly date back to its original form:
    function friendlyDate(str) {
      let friendly_date = str.replace(/-/g, '/').replace(/\+/g, ' ').replace(/_/g, ':');
      return friendly_date;
    }

    export { /*previously exported functions*/, friendlyDate };
When one of the rendered photos is pressed, the showPhoto function is executed. This updates the state to show the modal for viewing the full-size photo. The current_image stores the relevant data for the selected photo:
    showPhoto = (item) => {
      this.setState({
        is_photo_visible: true,
        current_image: {
          url: `${this.document_dir}${this.filename_prefix}${item.name}.jpg`,
          label: friendlyDate(item.name)
        }
      });
    }
Inside the render function, add the modal for viewing the photo. To make the image occupy the entire screen, add flex: 1 for the styling and ImageResizeMode should be contain. After the Image is the button for closing the photo and the label. Note that it should be rendered after the Image because you want it to be laid on top of the image. As an alternative, you can specify the zIndex style property:
    <Modal
      animationType="slide"
      transparent={false}
      visible={this.state.is_photo_visible}
      onRequestClose={
        this.setState({
          is_photo_visible: false
        });
      }>
      <View style={styles.modal}>
        {
          this.state.current_image &&
          <View style={styles.wrapper}>
            <Image
              source={{uri: this.state.current_image.url}}
              style={styles.wrapper}
              ImageResizeMode={"contain"} />

            <IconButton is_transparent={true} icon="close"
              styles={styles.close_button}
              onPress={this.closePhoto} />

            <View style={styles.photo_label}>
              <Text style={styles.photo_label_text}>{this.state.current_image.label}</Text>
            </View>
          </View>
        }
      </View>
    </Modal>
Lastly, update the styles:
    close_button: {
      position: 'absolute',
      top: 0,
      left: 0,
      padding: 10
    },
    photo_label: {
      position: 'absolute',
      bottom: 0,
      right: 0,
      padding: 5
    },
    photo_label_text: {
      color: '#FFF'
    },
Conclusion and next steps
That’s it! In this tutorial series, you’ve learned the basics of creating a React Native app. Over the course of three tutorials, you’ve built a fully functional workout tracking app. Along the way, you’ve learned how to add styles and functionality to a React Native app. You’ve also learned about React’s basic concepts such as UI componentization, state management, and the component lifecycle methods.
Now that you’ve got your hands dirty, it’s time to move on to the “real” React Native development. As mentioned in the first part of this series, we only made use of Expo in order to avoid the headaches which come with setting up a React Native development environment.
At the time of writing of this tutorial, Expo locks you in their platform until you “eject” your app to a plain React Native project. This means that you don’t have much choice on which tools and native packages to use for your app. You’re just locked into using the tools they provide. It’s the price you have to pay for the convenience that it provides.
If you want to continue developing apps with React Native, it’s important that you learn how to work with plain React Native. It’s a good thing that Expo provides two ways to convert an existing Expo project to a plain React Native project:
  • Eject to a plain React Native project – allows you to convert your Expo app to a plain React Native project. But all the code which uses any of Expo’s API’s needs to be updated to the plain React Native equivalent.
  • Eject to ExpoKit – the same as the above option, but it also ejects the Expo native libraries. This enables you to still use Expo’s API’s.
With that out of the way, here are a few topics that I recommend you to explore:
  • Setting up a React Native development environment – I have yet to find an up-to-date tutorial which shows how to set up an environment for the three most common operating systems (Windows, Mac OS, and Ubuntu). But here are a few good ones I can find:
    • Code: React Native: Setting Up the Environment
    • How to Install and Setup React Native on Ubuntu 17.10
    • Getting Started with React Native Development on Windows
  • Detaching Expo apps to ExpoKit
  • Awesome React Native ****- a collection of resources about React Native.
That’s all folks! I hope this series has given you the relevant skills to jump start your React Native development journey. The complete source code for this app is available on Github. Each part has their own branch so don’t for get to checkout the part3 branch.
The post Getting started with React Native – Part 3: Using native device functionality appeared first on Pusher Blog.