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
-
State Variables:
name
andaddress
: 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).
-
handleAddOrUpdate
Function:- If
editId
is notnull
, updates an existing entry. - If
editId
isnull
, adds a new entry with a randomid
. - Displays success messages using
Toast
.
- If
-
handleDelete
Function:- Deletes an entry by filtering out the item with the specified
id
. - Shows a success toast message.
- Deletes an entry by filtering out the item with the specified
-
handleEdit
Function:- Populates the form with the data of the item to be edited.
- Sets the
editId
to the item’sid
.
-
FlatList
:- Renders the list of entries.
- Each item has “Edit” and “Delete” buttons.
-
Toast Messages:
- Displays feedback for add, update, and delete operations using
react-native-toast-message
.
- Displays feedback for add, update, and delete operations using
-
Styling:
- Basic styles for the form, table, buttons, and layout.
4. Testing the CRUD Application
- Add: Fill out the name and address, then press “Add”. A new entry appears in the list below, and a success toast shows up.
- Edit: Press the “Edit” button on an entry. The form will populate with the entry’s data, allowing you to modify it. Press “Update” to save changes.
- Delete: Press the “Delete” button to remove an entry, with a toast confirming the deletion.
Summary
- React Native Components: Used
TextInput
,Button
,FlatList
, andTouchableOpacity
for building the UI. - State Management: Managed form input, data array, and edit mode using React hooks (
useState
). - CRUD Operations: Implemented create, read, update, and delete functionalities.
- Toast Notifications: Provided user feedback using
react-native-toast-message
.
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!