Skip to content

React Native Part 3 - CRUD with Static Data

Published: at 09:09 AM

React Native Basics (Part 3): Creating Buttons, Adding Routes, and Implementing Simple CRUD with Static Data

In Part 2, we explored basic components and learned how to build an APK with Expo Application Services (EAS). Now, let’s take it a step further by creating buttons, adding routes for navigation, and implementing simple CRUD (Create, Read, Update, Delete) functionality using a static array in React Native.

1. Creating Buttons for User Interaction

Buttons are essential components in any mobile app. Let’s start by creating some buttons in our app.

Example: Creating a Basic Button

import React from "react";
import { View, Button, Alert } from "react-native";

const App = () => {
  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
      <Button title="Press me" onPress={() => Alert.alert("Button pressed!")} />
    </View>
  );
};

export default App;

Here, we use the Button component from React Native. The onPress prop defines what happens when the button is pressed—in this case, it triggers an alert.

2. Adding Routes with React Navigation

For navigation between different screens in your app, we will use the react-navigation library.

Step 1: Install React Navigation

Run the following commands to install the required packages:

npm install @react-navigation/native
npm install @react-navigation/stack
npm install @react-navigation/native-stack
npm install react-native-screens react-native-safe-area-context

Step 2: Set Up Navigation

Create a new file called HomeScreen.js for our home screen and CRUDScreen.js for our CRUD operations. Here’s how to set up a simple stack navigator in App.js:

App.js

import React from "react";
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
import HomeScreen from "./HomeScreen";
import CRUDScreen from "./CRUDScreen";

const Stack = createStackNavigator();

const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="CRUD" component={CRUDScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default App;

In this code, we create a stack navigator with two routes: Home and CRUD.

Step 3: Creating the Home Screen with Navigation

HomeScreen.js

import React from "react";
import { View, Button } from "react-native";

const HomeScreen = ({ navigation }) => {
  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
      <Button
        title="Go to CRUD Screen"
        onPress={() => navigation.navigate("CRUD")}
      />
    </View>
  );
};

export default HomeScreen;

Here, we create a simple button that navigates to the CRUDScreen when pressed.

3. Implementing Simple CRUD with Static Data

Now that we have navigation set up, let’s implement a simple CRUD screen using a static array.

Step 1: Creating the CRUD Screen

CRUDScreen.js

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

const CRUDScreen = () => {
  const [items, setItems] = useState([{ id: "1", name: "Item 1" }]);
  const [input, setInput] = useState("");
  const [selectedId, setSelectedId] = useState(null);

  // Add Item
  const addItem = () => {
    if (input) {
      const newItem = { id: Date.now().toString(), name: input };
      setItems([...items, newItem]);
      setInput("");
    }
  };

  // Update Item
  const updateItem = () => {
    setItems(
      items.map(item =>
        item.id === selectedId ? { ...item, name: input } : item
      )
    );
    setInput("");
    setSelectedId(null);
  };

  // Delete Item
  const deleteItem = id => {
    setItems(items.filter(item => item.id !== id));
  };

  // Select Item for Editing
  const selectItem = item => {
    setInput(item.name);
    setSelectedId(item.id);
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="Enter item name"
        value={input}
        onChangeText={setInput}
      />
      <Button
        title={selectedId ? "Update Item" : "Add Item"}
        onPress={selectedId ? updateItem : addItem}
      />
      <FlatList
        data={items}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
          <View style={styles.itemContainer}>
            <Text>{item.name}</Text>
            <Button title="Edit" onPress={() => selectItem(item)} />
            <Button title="Delete" onPress={() => deleteItem(item.id)} />
          </View>
        )}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
  },
  input: {
    borderColor: "gray",
    borderWidth: 1,
    marginBottom: 10,
    padding: 8,
  },
  itemContainer: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    padding: 10,
    borderBottomWidth: 1,
    borderBottomColor: "#ccc",
  },
});

export default CRUDScreen;

Step 2: Explanation

Conclusion

In this part, we learned how to create buttons for user interaction, add routes using React Navigation, and implement a simple CRUD operation with a static array in React Native. These skills form the foundation of building interactive, multi-screen mobile apps.

Next, you can expand upon these concepts by integrating more complex data handling, such as using a database or API for persistent data storage. Happy coding!


Previous Post
React Native Part 2 - CRUD with Static Data
Next Post
React Native Part 4 - CRUD with Static Data