React Native Mini Project 2

Building React Native To-Do-App with Expo

React Native is a powerful framework for building mobile applications using JavaScript and React. In this blog, we will guide you through setting up your development environment and creating a simple To-Do application using React Native and Expo.

Prerequisites

Before getting started, ensure you have the following installed on your computer:

1. Install Node.js and npm

Node.js is required to run JavaScript code outside a browser, and npm (Node Package Manager) is used to install dependencies.

Download Node.js from the official website: Node.js Download

After installation, verify the installation by running the following commands in your terminal or command prompt:

				
					node -v
npm -v
				
			

2. Install Visual Studio Code

VS Code is a powerful code editor for JavaScript development. Download it from the official website: VS Code Download

Setting Up the Expo CLI

3. Install Expo CLI Globally

Expo is a framework that simplifies React Native development. Install it globally by running:

				
					npm install -g expo-cli
				
			

Creating a New React Native Project

4. Create a New Expo Project

To create a new React Native project using Expo, run the following command:

				
					npx expo init ToDoApp
				
			

Select the “Blank” template when prompted.

After the project is created, navigate into the project directory using below command:

				
					cd ToDoApp
				
			

Starting the Development Server

5. Start the React Native Development Server

Run the following command to install dependencies and start the Metro Bundler (the JavaScript bundler for React Native):

				
					npx expo install react-dom react-native-web @expo/metro-runtime
				
			

Installing UI Enhancements

6. Install React Native Gesture Handler

For better UI interactions, install React Native Gesture Handler by running:

				
					npm install react-native-gesture-handler
				
			

Creating a Simple To-Do App

7. Add To-Do List Code in App.js

Replace the content in App.js with the following code to create a simple To-Do application:

				
					import React, { useState } from "react";
import { View, Text, TextInput, TouchableOpacity, FlatList, StyleSheet, Animated } from "react-native";
import { Feather, AntDesign } from "@expo/vector-icons"; // For icons

export default function App() {
  const [task, setTask] = useState("");
  const [tasks, setTasks] = useState([]);
  const [editId, setEditId] = useState(null); // Track editing task
  const [fadeAnim] = useState(new Animated.Value(0)); // For smooth animations

  const handleAddOrEditTask = () => {
    if (task.trim() === "") return;
    
    if (editId) {
      setTasks(tasks.map((t) => (t.id === editId ? { ...t, text: task } : t)));
      setEditId(null);
    } else {
      setTasks([...tasks, { id: Date.now().toString(), text: task, completed: false }]);
    }
    
    setTask(""); // Clear input
  };

  const toggleTaskCompletion = (taskId) => {
    setTasks(tasks.map((t) => (t.id === taskId ? { ...t, completed: !t.completed } : t)));
  };

  const deleteTask = (taskId) => {
    setTasks(tasks.filter((t) => t.id !== taskId));
  };

  const editTask = (task) => {
    setTask(task.text);
    setEditId(task.id);
  };

  Animated.timing(fadeAnim, {
    toValue: 1,
    duration: 1000,
    useNativeDriver: true,
  }).start();

  return (
    <Animated.View style={[styles.container, { opacity: fadeAnim }]}>
      <Text style={styles.heading}>📝 To-Do List</Text>
      <View style={styles.inputContainer}>
        <TextInput
          style={styles.input}
          placeholder="Add a new task..."
          value={task}
          onChangeText={setTask}
        />
        <TouchableOpacity style={styles.addButton} onPress={handleAddOrEditTask}>
          <AntDesign name={editId ? "edit" : "pluscircle"} size={28} color="#fff" />
        </TouchableOpacity>
      </View>

      <FlatList
        data={tasks}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <View style={styles.taskItem}>
            <TouchableOpacity onPress={() => toggleTaskCompletion(item.id)} style={{ flex: 1 }}>
              <Text style={[styles.taskText, item.completed && styles.completedTask]}>
                {item.text}
              </Text>
            </TouchableOpacity>

            <TouchableOpacity onPress={() => editTask(item)}>
              <Feather name="edit" size={24} color="blue" />
            </TouchableOpacity>

            <TouchableOpacity onPress={() => deleteTask(item.id)}>
              <Feather name="trash-2" size={24} color="red" />
            </TouchableOpacity>
          </View>
        )}
      />
    </Animated.View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20, backgroundColor: "#9998ab" },
  heading: { fontSize: 28, fontWeight: "bold", textAlign: "center", color: "#fff", marginBottom: 20 },
  inputContainer: { flexDirection: "row", alignItems: "center", marginBottom: 20 },
  input: { flex: 1, borderWidth: 1, borderColor: "#555", padding: 12, borderRadius: 10, backgroundColor: "#444", color: "#fff" },
  addButton: { marginLeft: 10, backgroundColor: "#192336", padding: 12, borderRadius: 10 },
  taskItem: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", padding: 15, backgroundColor: "#333", borderRadius: 10, marginBottom: 10 },
  taskText: { fontSize: 18, color: "#fff", flex: 1 },
  completedTask: { textDecorationLine: "line-through", color: "gray" },
});

				
			

Running the Project

8. Run the Project on Web

To run the project in a web browser, execute the following command:

				
					npm run web
				
			

Before running the project, make sure to save all files. Any changes or updates should be saved before re-running the project.

9. View Your Running Project

Once the project is running, your browser will open automatically, displaying your React Native To-Do application.

Explanation of Code

10. Understanding the App Functionality

  • State Management: We use React’s useState to manage the task input and the list of tasks.
  • Add Task: When the user types in the TextInput field and presses the “Add Task” button, the task gets added to the tasks array.
  • Delete Task: Each task is displayed with a “Delete” button. Pressing it will remove that task from the list.
  • FlatList: This component is used to render the list of tasks efficiently.

Conclusion

Congratulations! You have successfully set up your development environment and built a simple React Native To-Do app using Expo. You can now explore more features and enhance your app further.

Happy coding! 🚀

Tech Amplifier Final Logo