Skip to content

React Native Part 7 - CRUD with Static Data

Published: at 09:09 AM

Step-by-Step Tutorial (Part 7): Creating a CRUD App in React Native

1. Setting Up the Project

If you haven’t already, create a new React Native project:

npx create-expo-app CrudApp
cd CrudApp
npm start

2. Installing Required Libraries

To show toast messages, we’ll use the react-native-toast-message package:

npm install react-native-toast-message

3. Creating the CRUD Application

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

App.js

import React, { useState } from "react";
import {
  View,
  Text,
  TextInput,
  Button,
  StyleSheet,
  FlatList,
  TouchableOpacity,
} from "react-native";
import Toast from "react-native-toast-message";

export default function App() {
  const [name, setName] = useState("");
  const [address, setAddress] = useState("");
  const [data, setData] = useState([]);
  const [editId, setEditId] = useState(null);

  // Handler to add or update data
  const handleAddOrUpdate = () => {
    if (name === "" || address === "") {
      Toast.show({
        type: "error",
        text1: "Error",
        text2: "Please fill out all fields.",
      });
      return;
    }

    if (editId !== null) {
      // Update existing entry
      setData(prevData =>
        prevData.map(item =>
          item.id === editId ? { ...item, name, address } : item
        )
      );
      setEditId(null);
      Toast.show({
        type: "success",
        text1: "Success",
        text2: "Data updated successfully!",
      });
    } else {
      // Add new entry
      const newEntry = {
        id: Math.random().toString(),
        name,
        address,
      };
      setData([...data, newEntry]);
      Toast.show({
        type: "success",
        text1: "Success",
        text2: "Data added successfully!",
      });
    }
    setName("");
    setAddress("");
  };

  // Handler to delete data
  const handleDelete = id => {
    setData(prevData => prevData.filter(item => item.id !== id));
    Toast.show({
      type: "success",
      text1: "Success",
      text2: "Data deleted successfully!",
    });
  };

  // Handler to edit data
  const handleEdit = item => {
    setName(item.name);
    setAddress(item.address);
    setEditId(item.id);
  };

  return (
    <View style={styles.container}>
      {/* Form for adding or editing */}
      <TextInput
        style={styles.input}
        placeholder="Name"
        value={name}
        onChangeText={setName}
      />
      <TextInput
        style={styles.input}
        placeholder="Address"
        value={address}
        onChangeText={setAddress}
      />
      <Button
        title={editId !== null ? "Update" : "Add"}
        onPress={handleAddOrUpdate}
      />

      {/* Table to display data */}
      <FlatList
        data={data}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
          <View style={styles.row}>
            <Text style={styles.column}>{item.id}</Text>
            <Text style={styles.column}>{item.name}</Text>
            <Text style={styles.column}>{item.address}</Text>
            <View style={styles.buttonGroup}>
              <TouchableOpacity
                style={styles.editButton}
                onPress={() => handleEdit(item)}
              >
                <Text style={styles.buttonText}>Edit</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.deleteButton}
                onPress={() => handleDelete(item.id)}
              >
                <Text style={styles.buttonText}>Delete</Text>
              </TouchableOpacity>
            </View>
          </View>
        )}
      />

      {/* Toast message */}
      <Toast />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    marginTop: 50,
  },
  input: {
    borderWidth: 1,
    borderColor: "#ccc",
    padding: 10,
    marginVertical: 5,
    borderRadius: 5,
  },
  row: {
    flexDirection: "row",
    justifyContent: "space-between",
    padding: 10,
    borderBottomWidth: 1,
    borderBottomColor: "#ccc",
    alignItems: "center",
  },
  column: {
    flex: 1,
    textAlign: "center",
  },
  buttonGroup: {
    flexDirection: "row",
  },
  editButton: {
    backgroundColor: "#4CAF50",
    padding: 5,
    marginHorizontal: 5,
    borderRadius: 5,
  },
  deleteButton: {
    backgroundColor: "#F44336",
    padding: 5,
    marginHorizontal: 5,
    borderRadius: 5,
  },
  buttonText: {
    color: "#fff",
  },
});

Code Explanation

  1. State Variables:

    • name and address: Stores the input values for the form.
    • data: An array holding the list of entries.
    • editId: Keeps track of which item is being edited (if any).
  2. handleAddOrUpdate Function:

    • If editId is not null, updates an existing entry.
    • If editId is null, adds a new entry with a random id.
    • Displays success messages using Toast.
  3. handleDelete Function:

    • Deletes an entry by filtering out the item with the specified id.
    • Shows a success toast message.
  4. handleEdit Function:

    • Populates the form with the data of the item to be edited.
    • Sets the editId to the item’s id.
  5. FlatList:

    • Renders the list of entries.
    • Each item has “Edit” and “Delete” buttons.
  6. Toast Messages:

    • Displays feedback for add, update, and delete operations using react-native-toast-message.
  7. Styling:

    • Basic styles for the form, table, buttons, and layout.

4. Testing the CRUD Application

Summary

You now have a basic CRUD app in React Native that displays a table of entries, allows adding, editing, and deleting them, and uses toast messages to confirm each action!


Previous Post
React Native Part 6 - CRUD with Static Data
Next Post
React Native Part 8 - CRUD with Static Data