Category: Example

https://cdn-icons-png.flaticon.com/512/5307/5307812.pnghttps://cdn-icons-png.flaticon.com/512/5307/5307812.png

  • Update the App to Use React Native Paper

    First, let’s integrate React Native Paper components into our app.

    Install Dependencies

    If you haven’t already, ensure you have the dependencies installed:

    bashCopy codenpm install react-native-paper
    

    You’ll also need to set up react-native-vector-icons for icons used in React Native Paper:

    bashCopy codenpm install react-native-vector-icons
    

    Update App.js

    Here’s an updated version of App.js that uses React Native Paper components:

    javascriptCopy codeimport React, { useEffect, useState } from 'react';
    import { StyleSheet, View, FlatList, Alert } from 'react-native';
    import { Provider as PaperProvider, TextInput, Button, List, Picker, Appbar } from 'react-native-paper';
    import AsyncStorage from '@react-native-async-storage/async-storage';
    
    const App = () => {
      const [items, setItems] = useState([]);
      const [textInput, setTextInput] = useState('');
      const [editIndex, setEditIndex] = useState(null);
      const [filter, setFilter] = useState('all');
      const [searchQuery, setSearchQuery] = useState('');
    
      useEffect(() => {
    
    const loadItems = async () => {
      try {
        const storedItems = await AsyncStorage.getItem('items');
        if (storedItems) {
          setItems(JSON.parse(storedItems));
        }
      } catch (error) {
        console.error(error);
      }
    };
    loadItems();
    }, []); useEffect(() => {
    const saveItems = async () => {
      try {
        await AsyncStorage.setItem('items', JSON.stringify(items));
      } catch (error) {
        console.error(error);
      }
    };
    saveItems();
    }, [items]); const addItem = () => {
    if (textInput.trim()) {
      const newItem = { key: textInput, completed: false };
      if (editIndex !== null) {
        const updatedItems = items.map((item, index) =>
          index === editIndex ? newItem : item
        );
        setItems(updatedItems);
        setEditIndex(null);
      } else {
        setItems([...items, newItem]);
      }
      setTextInput('');
    }
    }; const deleteItem = (itemToDelete) => {
    setItems(items.filter(item => item.key !== itemToDelete));
    }; const confirmDelete = (item) => {
    Alert.alert(
      'Delete Item',
      Are you sure you want to delete "${item.key}"?,
      [
        { text: 'Cancel', style: 'cancel' },
        { text: 'OK', onPress: () => deleteItem(item.key) },
      ],
      { cancelable: true }
    );
    }; const toggleCompletion = (item) => {
    const updatedItems = items.map(i =>
      i.key === item.key ? { ...i, completed: !i.completed } : i
    );
    setItems(updatedItems);
    }; const startEditing = (item, index) => {
    setTextInput(item.key);
    setEditIndex(index);
    }; // Filtering items based on the selected filter const filteredItems = items.filter(item => {
    const matchesFilter = (filter === 'all' || (filter === 'completed' && item.completed) || (filter === 'uncompleted' && !item.completed));
    const matchesSearch = item.key.toLowerCase().includes(searchQuery.toLowerCase());
    return matchesFilter && matchesSearch;
    }); return (
    <PaperProvider>
      <Appbar.Header>
        <Appbar.Content title="My Item List" />
      </Appbar.Header>
      <View style={styles.container}>
        <TextInput
          label="Add or edit an item"
          value={textInput}
          onChangeText={setTextInput}
          style={styles.input}
        />
        <Button mode="contained" onPress={addItem}>
          {editIndex !== null ? "Update Item" : "Add Item"}
        </Button>
        <TextInput
          label="Search items"
          value={searchQuery}
          onChangeText={setSearchQuery}
          style={styles.input}
        />
        <Picker
          selectedValue={filter}
          style={styles.picker}
          onValueChange={(itemValue) => setFilter(itemValue)}
        >
          <Picker.Item label="All" value="all" />
          <Picker.Item label="Completed" value="completed" />
          <Picker.Item label="Uncompleted" value="uncompleted" />
        </Picker>
        <FlatList
          data={filteredItems}
          renderItem={({ item }) => (
            <List.Item
              title={item.key}
              onPress={() => toggleCompletion(item)}
              right={props => (
                <Button onPress={() => startEditing(item)}>Edit</Button>
              )}
              onLongPress={() => confirmDelete(item)}
              style={[styles.item, item.completed && styles.completedItem]}
            />
          )}
          keyExtractor={(item) => item.key}
        />
      </View>
    </PaperProvider>
    ); }; const styles = StyleSheet.create({ container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#fff',
    }, input: {
    marginBottom: 10,
    }, picker: {
    height: 50,
    width: 150,
    marginBottom: 10,
    }, item: {
    padding: 10,
    }, completedItem: {
    textDecorationLine: 'line-through',
    color: 'gray',
    }, }); export default App;
  • Implement Filtering Functionality

    Let’s start by adding a filter feature. Here’s how you can modify your App.js to include filtering options.

    Updated Code for App.js

    javascriptCopy codeimport React, { useEffect, useState } from 'react';
    import { StyleSheet, Text, View, FlatList, TextInput, Button, TouchableOpacity, Alert, Picker } from 'react-native';
    import AsyncStorage from '@react-native-async-storage/async-storage';
    
    const App = () => {
      const [items, setItems] = useState([]);
      const [textInput, setTextInput] = useState('');
      const [editIndex, setEditIndex] = useState(null);
      const [filter, setFilter] = useState('all');
    
      useEffect(() => {
    
    const loadItems = async () => {
      try {
        const storedItems = await AsyncStorage.getItem('items');
        if (storedItems) {
          setItems(JSON.parse(storedItems));
        }
      } catch (error) {
        console.error(error);
      }
    };
    loadItems();
    }, []); useEffect(() => {
    const saveItems = async () => {
      try {
        await AsyncStorage.setItem('items', JSON.stringify(items));
      } catch (error) {
        console.error(error);
      }
    };
    saveItems();
    }, [items]); const addItem = () => {
    if (textInput.trim()) {
      const newItem = { key: textInput, completed: false };
      if (editIndex !== null) {
        const updatedItems = items.map((item, index) =>
          index === editIndex ? newItem : item
        );
        setItems(updatedItems);
        setEditIndex(null);
      } else {
        setItems([...items, newItem]);
      }
      setTextInput('');
    }
    }; const deleteItem = (itemToDelete) => {
    setItems(items.filter(item => item.key !== itemToDelete));
    }; const confirmDelete = (item) => {
    Alert.alert(
      'Delete Item',
      Are you sure you want to delete "${item.key}"?,
      [
        { text: 'Cancel', style: 'cancel' },
        { text: 'OK', onPress: () => deleteItem(item.key) },
      ],
      { cancelable: true }
    );
    }; const toggleCompletion = (item) => {
    const updatedItems = items.map(i =>
      i.key === item.key ? { ...i, completed: !i.completed } : i
    );
    setItems(updatedItems);
    }; const startEditing = (item, index) => {
    setTextInput(item.key);
    setEditIndex(index);
    }; // Filtering items based on the selected filter const filteredItems = items.filter(item => {
    if (filter === 'completed') return item.completed;
    if (filter === 'uncompleted') return !item.completed;
    return true; // 'all'
    }); return (
    <View style={styles.container}>
      <Text style={styles.title}>My Item List</Text>
      <TextInput
        style={styles.input}
        placeholder="Add or edit an item"
        value={textInput}
        onChangeText={setTextInput}
      />
      <Button title={editIndex !== null ? "Update Item" : "Add Item"} onPress={addItem} />
      
      {/* Filter Picker */}
      <Picker
        selectedValue={filter}
        style={styles.picker}
        onValueChange={(itemValue) => setFilter(itemValue)}
      >
        <Picker.Item label="All" value="all" />
        <Picker.Item label="Completed" value="completed" />
        <Picker.Item label="Uncompleted" value="uncompleted" />
      </Picker>
      <FlatList
        data={filteredItems}
        renderItem={({ item, index }) => (
          <TouchableOpacity onLongPress={() => confirmDelete(item)} onPress={() => toggleCompletion(item)}>
            <Text style={[styles.item, item.completed && styles.completedItem]}>
              {item.key}
            </Text>
            <Button title="Edit" onPress={() => startEditing(item, index)} />
          </TouchableOpacity>
        )}
        keyExtractor={(item) => item.key}
      />
    </View>
    ); }; const styles = StyleSheet.create({ container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#fff',
    }, title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
    }, input: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    marginBottom: 10,
    paddingHorizontal: 10,
    }, picker: {
    height: 50,
    width: 150,
    marginBottom: 10,
    }, item: {
    padding: 10,
    fontSize: 18,
    borderBottomColor: '#ccc',
    borderBottomWidth: 1,
    }, completedItem: {
    textDecorationLine: 'line-through',
    color: 'gray',
    }, }); export default App;
  • Update the Item Structure

    First, modify the way items are structured to include a completed state. We’ll adjust the addItem, deleteItem, and other relevant functions accordingly.

    Updated Code for App.js

    Here’s the updated code:

    javascriptCopy codeimport React, { useEffect, useState } from 'react';
    import { StyleSheet, Text, View, FlatList, TextInput, Button, TouchableOpacity, Alert } from 'react-native';
    import AsyncStorage from '@react-native-async-storage/async-storage';
    
    const App = () => {
      const [items, setItems] = useState([]);
      const [textInput, setTextInput] = useState('');
      const [editIndex, setEditIndex] = useState(null);
    
      useEffect(() => {
    
    const loadItems = async () => {
      try {
        const storedItems = await AsyncStorage.getItem('items');
        if (storedItems) {
          setItems(JSON.parse(storedItems));
        }
      } catch (error) {
        console.error(error);
      }
    };
    loadItems();
    }, []); useEffect(() => {
    const saveItems = async () => {
      try {
        await AsyncStorage.setItem('items', JSON.stringify(items));
      } catch (error) {
        console.error(error);
      }
    };
    saveItems();
    }, [items]); const addItem = () => {
    if (textInput.trim()) {
      const newItem = { key: textInput, completed: false };
      if (editIndex !== null) {
        const updatedItems = items.map((item, index) =>
          index === editIndex ? newItem : item
        );
        setItems(updatedItems);
        setEditIndex(null);
      } else {
        setItems([...items, newItem]);
      }
      setTextInput('');
    }
    }; const deleteItem = (itemToDelete) => {
    setItems(items.filter(item => item.key !== itemToDelete));
    }; const confirmDelete = (item) => {
    Alert.alert(
      'Delete Item',
      Are you sure you want to delete "${item.key}"?,
      [
        { text: 'Cancel', style: 'cancel' },
        { text: 'OK', onPress: () => deleteItem(item.key) },
      ],
      { cancelable: true }
    );
    }; const toggleCompletion = (item) => {
    const updatedItems = items.map(i =>
      i.key === item.key ? { ...i, completed: !i.completed } : i
    );
    setItems(updatedItems);
    }; const startEditing = (item, index) => {
    setTextInput(item.key);
    setEditIndex(index);
    }; return (
    <View style={styles.container}>
      <Text style={styles.title}>My Item List</Text>
      <TextInput
        style={styles.input}
        placeholder="Add or edit an item"
        value={textInput}
        onChangeText={setTextInput}
      />
      <Button title={editIndex !== null ? "Update Item" : "Add Item"} onPress={addItem} />
      <FlatList
        data={items}
        renderItem={({ item, index }) => (
          <TouchableOpacity onLongPress={() => confirmDelete(item)} onPress={() => toggleCompletion(item)}>
            <Text style={[styles.item, item.completed && styles.completedItem]}>
              {item.key}
            </Text>
            <Button title="Edit" onPress={() => startEditing(item, index)} />
          </TouchableOpacity>
        )}
        keyExtractor={(item) => item.key}
      />
    </View>
    ); }; const styles = StyleSheet.create({ container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#fff',
    }, title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
    }, input: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    marginBottom: 10,
    paddingHorizontal: 10,
    }, item: {
    padding: 10,
    fontSize: 18,
    borderBottomColor: '#ccc',
    borderBottomWidth: 1,
    }, completedItem: {
    textDecorationLine: 'line-through',
    color: 'gray',
    }, }); export default App;
  • Install AsyncStorage

    You need to install the @react-native-async-storage/async-storage package. Run the following command in your project directory:

    bashCopy codenpm install @react-native-async-storage/async-storage
    

    Step 2: Update App.js

    Replace the existing code in App.js with the following code:

    javascriptCopy codeimport React, { useEffect, useState } from 'react';
    import { StyleSheet, Text, View, FlatList, TextInput, Button, TouchableOpacity, Alert } from 'react-native';
    import AsyncStorage from '@react-native-async-storage/async-storage';
    
    const App = () => {
      const [items, setItems] = useState([]);
      const [textInput, setTextInput] = useState('');
    
      // Load items from AsyncStorage on app start
      useEffect(() => {
    
    const loadItems = async () => {
      try {
        const storedItems = await AsyncStorage.getItem('items');
        if (storedItems) {
          setItems(JSON.parse(storedItems));
        }
      } catch (error) {
        console.error(error);
      }
    };
    loadItems();
    }, []); // Save items to AsyncStorage whenever they change useEffect(() => {
    const saveItems = async () => {
      try {
        await AsyncStorage.setItem('items', JSON.stringify(items));
      } catch (error) {
        console.error(error);
      }
    };
    saveItems();
    }, [items]); const addItem = () => {
    if (textInput.trim()) {
      setItems([...items, { key: textInput }]);
      setTextInput('');
    }
    }; const deleteItem = (itemToDelete) => {
    setItems(items.filter(item => item.key !== itemToDelete));
    }; const confirmDelete = (item) => {
    Alert.alert(
      'Delete Item',
      Are you sure you want to delete "${item.key}"?,
      [
        { text: 'Cancel', style: 'cancel' },
        { text: 'OK', onPress: () => deleteItem(item.key) },
      ],
      { cancelable: true }
    );
    }; return (
    <View style={styles.container}>
      <Text style={styles.title}>My Item List</Text>
      <TextInput
        style={styles.input}
        placeholder="Add a new item"
        value={textInput}
        onChangeText={setTextInput}
      />
      <Button title="Add Item" onPress={addItem} />
      <FlatList
        data={items}
        renderItem={({ item }) => (
          <TouchableOpacity onLongPress={() => confirmDelete(item)}>
            <Text style={styles.item}>{item.key}</Text>
          </TouchableOpacity>
        )}
        keyExtractor={(item) => item.key}
      />
    </View>
    ); }; const styles = StyleSheet.create({ container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#fff',
    }, title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
    }, input: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    marginBottom: 10,
    paddingHorizontal: 10,
    }, item: {
    padding: 10,
    fontSize: 18,
    borderBottomColor: '#ccc',
    borderBottomWidth: 1,
    }, }); export default App;
  • Set Up Your Project

    First, make sure you have React Native set up. If you haven’t set up a project yet, you can create one using the following command:

    bashCopy codenpx react-native init MyAwesomeApp
    

    Step 2: Create a Simple List App

    Now, you can replace the contents of App.js with the following code:

    javascriptCopy codeimport React, { useState } from 'react';
    import { StyleSheet, Text, View, FlatList, TextInput, Button } from 'react-native';
    
    const App = () => {
      const [items, setItems] = useState([]);
      const [textInput, setTextInput] = useState('');
    
      const addItem = () => {
    
    if (textInput.trim()) {
      setItems([...items, { key: textInput }]);
      setTextInput('');
    }
    }; return (
    <View style={styles.container}>
      <Text style={styles.title}>My Item List</Text>
      <TextInput
        style={styles.input}
        placeholder="Add a new item"
        value={textInput}
        onChangeText={setTextInput}
      />
      <Button title="Add Item" onPress={addItem} />
      <FlatList
        data={items}
        renderItem={({ item }) => <Text style={styles.item}>{item.key}</Text>}
        keyExtractor={(item) => item.key}
      />
    </View>
    ); }; const styles = StyleSheet.create({ container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#fff',
    }, title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
    }, input: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    marginBottom: 10,
    paddingHorizontal: 10,
    }, item: {
    padding: 10,
    fontSize: 18,
    borderBottomColor: '#ccc',
    borderBottomWidth: 1,
    }, }); export default App;

    Step 3: Run Your App

    To run your app, use the following command in your project directory:

    bashCopy codenpx react-native run-android
    

    or

    bashCopy codenpx react-native run-ios