Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
React Native By Example
React Native By Example

React Native By Example: Native mobile development with React

eBook
$27.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

React Native By Example

Advanced Functionality and Styling the To-Do List App

Having built an MVP for Tasks, our to-do list app, it's time to delve into building out advanced functionality, and styling the application to make it look nice. This chapter will explore the following topics:

  • Utilizing the NavigatorIOS component to build an edit screen to add details to a task
  • Taking in a date and time for tasks to be due with DatePickerIOS
  • Creating a custom collapsible component for our app and utilizing LayoutAnimation to give us fluid transitions
  • Building a Button component for our UI to clear a to-do item's due date
  • Saving the data of an edited task and rendering a due date, if applicable
  • Porting the application over to Android, swapping out DatePickerIOS for DatePickerAndroid and TimePickerAndroid and NavigatorIOS for Navigator, and exploring the control flow in deciding which component is used
...

Navigator and NavigatorIOS

Implementing navigation in a mobile application helps us control how our users interact with and experience our apps. It lets us assign context to situations that would otherwise not have any--for example, in Tasks, it will not make sense to show a user an edit view for a task that they haven't selected; only showing this to the user when they select a task to edit builds situational context and awareness.

React Native's Navigator component handles the transitions between different views in your application. Glancing at the documentation, you may note that there's both a Navigator and NavigatorIOS component. Navigator is available on iOS and Android and implemented with JavaScript. On the other hand, NavigatorIOS is specifically available for iOS and is a wrapper around iOS's native UINavigationController, animating it and behaving the way you would expect from any...

Using DatePickerIOS

A key feature in Tasks is the ability to set a reminder for when a task is due. Ideally, our users can set a day as well as a time for when a task should be completed so that they can be reminded of the due date. To accomplish this, we'll use an iOS component named DatePickerIOS. This is a component that renders a date and time selector that we can utilize in our application.

Listed here are the two props that we will be using with our DatePickerIOS component. Other props exist in the React Native documentation in case you are interested:

  • date: This is one of the two required props that track the current selected date. Ideally, this information is stored within the state of the component that renders DatePickerIOS. The date should be an instance of the Date object in JavaScript.
  • onDateChange: This is the other required prop and is fired when a user changes the date or time...

Using onLayout

In our preceding example, we don't need to specify the height of the DatePickerIOS component when expanded. However, there may be scenarios in which you may need to manually get the dimensions of a component.

To calculate a component's height, we can utilize its onLayout property to fire a callback and then use that callback to save properties passed to the callback. The onLayout property is an event that is invoked on mount and layout changes, giving the event object a nativeEvent object that nests the component's layout properties. Using DatePickerIOS as an example, you can pass a callback to its onLayout prop like this:

<DatePickerIOS 
date={ this.state.date }
onDateChange={ (date) => this._onDateChange(date) }
onLayout={ (event) => this._getComponentDimensions(event) }
style={ styles.datePicker }
/>

The event from onLayout gives access to the following...

Button

Let's build a clear due date button for the EditTask component and only selectively enable it if a due date has been selected for the to-do item. The Button component in React Native should help us render one quickly.

The Button component accepts a couple of props; the following four will be used in our application:

  • color: This is a string (or stringified hex) that sets either the text color on iOS or the background color on Android
  • disabled: This is a Boolean that disables the button if set to true; it defaults to false
  • onPress: This is a callback that is fired when a button is pressed
  • title: This is the text to display within the button

A sample Button component can be rendered like this:

<Button 
color={ 'blue' }
disabled={ this.state.buttonDisabled }
onPress={ () => alert('Submit button pressed') }
title={ 'Submit' }
/>

Modify EditTask...

Navigator and NavigatorIOS


Implementing navigation in a mobile application helps us control how our users interact with and experience our apps. It lets us assign context to situations that would otherwise not have any--for example, in Tasks, it will not make sense to show a user an edit view for a task that they haven't selected; only showing this to the user when they select a task to edit builds situational context and awareness.

React Native's Navigator component handles the transitions between different views in your application. Glancing at the documentation, you may note that there's both a Navigator and NavigatorIOS component. Navigator is available on iOS and Android and implemented with JavaScript. On the other hand, NavigatorIOS is specifically available for iOS and is a wrapper around iOS's native UINavigationController, animating it and behaving the way you would expect from any iOS application.

Later in this chapter, we will take a closer look at the Navigator.

Note

An important...

Using DatePickerIOS


A key feature in Tasks is the ability to set a reminder for when a task is due. Ideally, our users can set a day as well as a time for when a task should be completed so that they can be reminded of the due date. To accomplish this, we'll use an iOS component named DatePickerIOS. This is a component that renders a date and time selector that we can utilize in our application.

Listed here are the two props that we will be using with our DatePickerIOS component. Other props exist in the React Native documentation in case you are interested:

  • date: This is one of the two required props that track the current selected date. Ideally, this information is stored within the state of the component that renders DatePickerIOS. The date should be an instance of the Date object in JavaScript.
  • onDateChange: This is the other required prop and is fired when a user changes the date or time in the component. It accepts one argument, which is the Date object representing the new date and time...

Using onLayout


In our preceding example, we don't need to specify the height of the DatePickerIOS component when expanded. However, there may be scenarios in which you may need to manually get the dimensions of a component.

To calculate a component's height, we can utilize its onLayout property to fire a callback and then use that callback to save properties passed to the callback. The onLayout property is an event that is invoked on mount and layout changes, giving the event object a nativeEvent object that nests the component's layout properties. Using DatePickerIOS as an example, you can pass a callback to its onLayout prop like this:

<DatePickerIOS 
  date={ this.state.date } 
  onDateChange={ (date) => this._onDateChange(date) } 
  onLayout={ (event) => this._getComponentDimensions(event) } 
  style={ styles.datePicker }  
/> 

 

The event from onLayout gives access to the following property:

event: { 
  nativeEvent: { 
    layout: { 
      x: //some number 
      y: //some number...

Button


Let's build a clear due date button for the EditTask component and only selectively enable it if a due date has been selected for the to-do item. The Button component in React Native should help us render one quickly.

The Button component accepts a couple of props; the following four will be used in our application:

  • color: This is a string (or stringified hex) that sets either the text color on iOS or the background color on Android
  • disabled: This is a Boolean that disables the button if set to true; it defaults to false
  • onPress: This is a callback that is fired when a button is pressed
  • title: This is the text to display within the button

A sample Button component can be rendered like this:

<Button 
  color={ 'blue' } 
  disabled={ this.state.buttonDisabled } 
  onPress={ () => alert('Submit button pressed') } 
  title={ 'Submit' }  
/> 

Modify EditTask so that it has the following features:

  • It contains a Boolean, titled expanded, in its state to control the open/closed status of...

Switch


Switch is a component that renders a Boolean input and allows the user to toggle back and forth.

With Switch, these are the props that we will use:

  • onValueChange: This is a callback that is invoked with the new value of the switch when the value changes
  • value: This is a Boolean that determines whether the switch is set to its 'on' position or not; it defaults to false

A simple Switch component can look like this:

<Switch 
  onValueChange={ (value) =? this.setState({ toggled: value })} 
  value={ this.state.toggled } 
/> 

As stated earlier, Switch has two props that are required: its value and a callback to change its value when toggled.

Using this knowledge, let's make changes to the TasksList component so that it passes the completed, due, formattedDate, and text properties of each row to the EditTask component for use.

Then, make additions to the EditTask component so that it:

  • Expects the completed, due, formattedDate, and text props as part of its propTypes declaration.
  • Contains a...

Save button


In this section, we will create a button in the upper-right corner of the navigation bar that is labeled as Save. When it is tapped on, the following two things must happen:

  • The changes the user made to the to-do item (such as its name, completion status, and due date) must be saved to AsyncStorage, overwriting its previous details
  • The TasksList must be updated so that the user visually sees the changes they made right away

Rendering the Save button is easy with React Native. The object that gets pushed to NavigatorIOS needs to receive the following two key/value pairs:

  • rightButtonTitle: This is a string that renders the text shown in that area
  • onRightButtonPress: This is a callback that is fired when that button is pressed

At face value, this looks simple. However, we can't pass any information to the onRightButtonPress method of NavigatorIOS from a rendered child. Instead, we have to keep a copy of the changes we make inside our TasksList component as well, and update them as the...

TasksListCell modifications


Finally, we want to edit each row rendered by our ListView to display the due date, if one exists.

To do this, we will have to write some conditional logic to show the formatted date, if one is assigned to the to-do item we are rendering. This is also a good time to create a custom styles folder for this component as we will be needing it.

Spend some time creating your version of this feature. My solution is as follows:

// Tasks/app/components/TasksListCell/index.js 

... 
import styles from './styles'; 

You might notice from the above import statement that TasksListCell now imports its StyleSheet.

Add formattedDate to propTypes as an optional string:

export default class TasksListCell extends Component { 
  static propTypes = { 
    ... 
    formattedDate: PropTypes.string, 
  } 
... 
  render () { 
    ... 
    return ( 
      <View style={ styles.tasksListCellContainer }> 
        <TouchableHighlight 
          ... 
        > 
          <View style...

Navigator


The Navigator component works a bit differently from its native iOS component, but it's still very powerful to work with. One of the changes with using Navigator is that your routes should be explicitly defined. We can do this by setting up an array of routes and rendering a specific scene based on which route we're accessing. Here's a sample:

export default class Tasks extends Component { 
  render () { 
    const routes = [ 
      { title: 'First Component', index: 0 }, 
      { title: 'Second Component', index: 1 } 
    ]; 

Create a routes array, as shown in the preceding code.

You might notice that we are explicitly defining our routes from the beginning, setting up an initial route and then passing in props to each route's component here:

    return ( 
      <Navigator 
        initialRoute={{ index: 0 }} 
        renderScene={ (routes, navigator) => 
        this._renderScene(routes, navigator) } /> 
    ) 
  } 

The route object passed in to _renderScene contains a passProps...

Platform


When your files have such little variance in the differences between their iOS and Android functionalities, it's okay to use the same file. Utilizing the Platform API, we can identify the type of mobile device the user is on and conditionally send them down a specific path.

Import the Platform API along with the rest of your React Native components:

import { Platform } from 'react-native';  

Then call its OS property within a component:

  _platformConditional () { 
    if (Platform.OS === 'ios') { 
      doSomething(); 
    } 

    if (Platform.OS === 'android') { 
      doSomethingElse(); 
    } 
  } 

This lets us control the path our app takes and allows for a little bit of code reuse.

Note

Android-specific filesIf we need to create a file that is supposed to only run on Android devices, simply name it <FILENAME>.android.js, just like the two index files. React Native will know exactly which file to build with, and this lets us create components that are platform-specific when...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Work on native APIs and UI Elements using React Native
  • Get the best of both worlds: the power of native approach and the fluidity of JavaScript
  • Create increasingly complex real-world applications and dive deeper into React Native

Description

React Native's ability to build performant mobile applications with JavaScript has resulted in its popularity amongst developers. Developers now have the luxury to create incredible mobile experiences that look and feel native to their platforms with the comfort of a well-known language and the popular React.js library. This book will show you how to build your own native mobile applications for the iOS and Android platforms while leveraging the finesse and simplicity of JavaScript and React. Throughout the book you will build three projects, each of increasing complexity. You will also link up with the third-party Facebook SDK, convert an app to support the Redux architecture, and learn the process involved in making your apps available for sale on the iOS App Store and Google Play. At the end of this book, you will have learned and implemented a wide breadth of core APIs and components found in the React Native framework that are necessary in creating great mobile experiences.

Who is this book for?

If you are keen on learning to use the revolutionary mobile development tool React Native to build native mobile applications, then this book is for you. Prior experience with JavaScript would be useful.

What you will learn

  • How to create mobile-performant iOS and Android apps using JavaScript and React
  • The potential of each API and component, putting them into practice throughout the course of three projects
  • The process of integrating the Facebook SDK to build an app that connects to third-party data
  • Every step taken to implement Redux, a popular state management library, in your mobile apps
  • The requirements for building and deploying your apps to market, with detailed instructions on how to release and beta test apps on both the Apple App Store and Google Play

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 24, 2017
Length: 414 pages
Edition : 1st
Language : English
ISBN-13 : 9781786464750
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Apr 24, 2017
Length: 414 pages
Edition : 1st
Language : English
ISBN-13 : 9781786464750
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 152.97
React and React Native
$54.99
React Native By Example
$48.99
Mastering React Native
$48.99
Total $ 152.97 Stars icon

Table of Contents

9 Chapters
First Project - Creating a Basic To-Do List App Chevron down icon Chevron up icon
Advanced Functionality and Styling the To-Do List App Chevron down icon Chevron up icon
Our Second Project - The Budgeting App Chevron down icon Chevron up icon
Advanced Functionality with the Expenses App Chevron down icon Chevron up icon
Third Project - The Facebook Client Chevron down icon Chevron up icon
Advanced Facebook App Functionality Chevron down icon Chevron up icon
Redux Chevron down icon Chevron up icon
Deploying Your Applications Chevron down icon Chevron up icon
Additional React Native Components Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.7
(3 Ratings)
5 star 66.7%
4 star 0%
3 star 0%
2 star 0%
1 star 33.3%
Alexxis Johnson Oct 20, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book helped me understand React Native, and now I can use the technology to build my own apps. I definitely recommend checking it out!
Amazon Verified review Amazon
Peenmaster Oct 20, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very helpful book, helped clear up a lot of the problems I was having trying to learn in my own.
Amazon Verified review Amazon
Eugeniu Jul 07, 2017
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Compared to similar programming books I have read, this book has been the most frustrating because it is unclear and contains too many inconsistencies and errors. The book alternates for no reason between "let's implement a feature, here's the code you need" and "let's implement a feature, write the code yourself, but here's some of the code I used." For example, in the TextInput section, the author writes "Take some time to try and add this first feature into our app! In the next section, I will share some screenshots of my results and break down the code I wrote for it." and "Let's look at the code to see how I tackled it--yours may be different!"Well, his code doesn't even work. His "Tasks/app/components/TasksList/styles.js" code only contains a style for "container", but his "Tasks/app/components/TasksList/index.js" code references "styles.textInput". Without that style, the TextInput was in the wrong place. I actually had to look for the code in the accompanying GitHub repository to find the correct code.Even so, my app didn't work right. I copied everything from the book, but after inputting a task, the ListView would not get updated. Then I went to GitHub again. I copied the entire contents of index.ios.js, TasksList/index.js, and TasksList/styles.js. I still had the same problem. I am new to React Native, but given that I copy-pasted only the author's code and none of my own code, I have to conclude that it's a problem with the book and accompanying code.Maybe the problem is that I am using the wrong React Native version (I am using 0.45). If that's the case, that's still the book's problem. Nowhere in the book does it tell you what version to use. If I'm reading a book on native iOS development, it will say "this book uses Swift 3 with Xcode 8 and iOS 10. If you're using different versions, you may have problems." This book doesn't do that.Maybe the problem is that I'm not seeing something obvious to others. That's possible. But if that's the case, there is no online community around this book, like there is with Big Nerd Ranch books, so I don't have anywhere I can easily ask questions. The book also does not suggest I can contact the author. The only thing it says is: "To send us general feedback, simply e-mail feedback@packtpub.com, and mention the book's title in the subject of your message." That won't help me.If anyone can show that I'm wrong about this, I'd be happy to take this review down.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.