This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Add a Complete Toggle with React Native Switch

3:19 React lesson by

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.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

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.

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.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?