Browse Source

Video 4: Add a Toggle Button with React Native TouchableOpacity.

Frederic G. MARAND 7 years ago
parent
commit
6dd29ba43d
2 changed files with 38 additions and 4 deletions
  1. 24 3
      app.js
  2. 14 1
      header.js

+ 24 - 3
app.js

@@ -1,5 +1,10 @@
 import React, { Component } from "react";
-import { View, Text, StyleSheet, Platform } from "react-native";
+import {
+  Platform,
+  StyleSheet,
+  Text,
+  View
+} from "react-native";
 import Header from "./header";
 import Footer from "./footer";
 
@@ -22,10 +27,12 @@ class App extends Component {
   constructor(props) {
     super(props);
     this.state = {
-      value: "",
-      items: []
+      allComplete: false,
+      items: [],
+      value: ""
     };
     this.handleAddItem = this.handleAddItem.bind(this);
+    this.handleToggleAllComplete = this.handleToggleAllComplete.bind(this);
   }
 
   handleAddItem() {
@@ -46,6 +53,19 @@ class App extends Component {
     });
   }
 
+  handleToggleAllComplete() {
+    const complete = !this.state.allComplete;
+    const newItems = this.state.items.map((item) => ({
+      ...item,
+      complete
+    }));
+    console.table(newItems);
+    this.setState({
+      allComplete: complete,
+      items: newItems
+    });
+  }
+
   render() {
     console.log(this.state);
     return (
@@ -53,6 +73,7 @@ class App extends Component {
         <Header
           onAddItem={this.handleAddItem}
           onChange={(value) => this.setState({ value })}
+          onToggleAllComplete={this.handleToggleAllComplete}
           value={this.state.value}
         />
         <View style={styles.content} />

+ 14 - 1
header.js

@@ -3,9 +3,12 @@ import {
   StyleSheet,
   Text,
   TextInput,
+  TouchableOpacity,
   View
 } from 'react-native';
 
+const CHECKMARK = String.fromCharCode(10003);
+
 const styles = StyleSheet.create({
   header: {
     paddingHorizontal: 16,
@@ -15,7 +18,12 @@ const styles = StyleSheet.create({
   },
   input: {
     flex: 1,
-    height: 50
+    height: 50,
+    marginLeft: 16
+  },
+  toggleIcon: {
+    color: "#CCC",
+    fontSize: 30
   }
 });
 
@@ -23,6 +31,11 @@ class Header extends Component {
   render() {
     return (
       <View style={styles.header}>
+        <TouchableOpacity
+          onPress={this.props.onToggleAllComplete}
+        >
+          <Text style={styles.toggleIcon}>{CHECKMARK}</Text>
+        </TouchableOpacity>
         <TextInput
           blurOnSubmit={false}
           onChangeText={this.props.onChange}