This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Add a Complete Toggle with React Native Switch

    Jason BrownJason Brown

    We'll add a cross platform Switch component to toggle the completeness of each todo item. We'll show how to pass down functions from the parent application to the child row of a ListView.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 Start by importing Switch from react-native. We'll then render our switch and pass in value={this.props.complete}. Now, when we refresh, we add an item, "This is a todo," to the list, we can see now there is a switch item being rendered, and we can toggle that with our toggle all complete.

    00:24 Our text is now slammed to the end, we'll wrap our text in a view, we'll then create a textWrap style. We'll give it flex:1, as well as marginHorizontal of 10, to add 10 pixels of margin on both sides.

    00:47 Then apply that, style={styles.textWrap}. We refresh, add an item, "this is a todo." We'll see now the text is back to where it started. Now, we'll go add a complete style, which we'll apply to our text when the item becomes complete.

    01:09 We'll say textDecorationLine, we'll give a value of line-through. We'll then go destruct our complet from this.props, we'll change this to just complete. We'll switch over our styles on our text to an array, and say complete && styles.complete. This will apply the styles.complete style when the thing becomes complete.

    01:35 When we refresh and add an item, and then toggle our completion status, we can see that the text becomes struck through. We'll now add an onValueChange function to our switch, and say {this.props.onComplete}.

    01:55 We'll go to our app, we'll create a handleToggleComplete, which will take a key and a completion status, then, we'll say const newItems = this.state.items, and we'll map over each of our items.

    02:19 Inside here, if we say if item.key doesn't equal the key that we're looking for, then, we'll just return the old item, otherwise, we'll return item that's read in, and then add the new complete flag. Then, we can say this.setSource(newItems, newItems).

    02:37 Now, we'll go bind our handleToggleComplete. We'll now pass in onComplete equals a function this.handleToggleComplete, which will pass in our key, and the complete value that gets passed back up to us. Now when we refresh, add an item, you can toggle the completion status at the row level.

    Discuss

    Discuss