Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Add a Complete Toggle with React Native Switch

    react-nativeReact Native
    0.35 - 0.37

    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.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    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.

    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.

    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.

    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.

    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}.

    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.

    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).

    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.