Notes Application in React Native Part 2

Cover Image for Notes Application in React Native Part 2
Rajeshkumar S
Rajeshkumar S
about 1 month ago
appmobiledevelopmentandroidReact Nativenotesapplication

Introduction

In the previous tutorial, we set up the project for our notes application in React Native. In this tutorial, we will continue building the application by add the functionality to edit and delete notes. Users will be able to edit the content of their notes and delete notes they no longer need.

const onHandlePress = () => {
  if (editedNoteId !== null) {
    // If we're editing an existing note
    setNotesList((prev) =>
      prev.map((note) => {
        if (note.id === editedNoteId) {
          return {
            ...note,
            title: newNotes,
          };
        }
        return note;
      })
    );
    setEditedNoteId(null); // Reset editedNoteId since editing is done
  } else {
    // If we're adding a new note
    setNotesList((prev) => [
      ...prev,
      {
        id: notesList.length + 1, // Generate a unique ID for the new note
        title: newNotes, // Set the title of the new note to newNotes
      },
    ]);
  }
  setNewNotes(""); // Clear the input field for newNotes
};

If editedNoteId is not null, it means we're editing an existing note. In this case, it updates the notesList array by mapping over each note. If the note's ID matches the editedNoteId, it updates its title with the value of newNotes. Otherwise, it returns the note unchanged. After updating the list, it sets editedNoteId to null to indicate that editing is complete.

If editedNoteId is null, it means we're adding a new note. It appends a new note object to the notesList array. T he new note gets a unique ID (one higher than the length of the current list), and its title is set to the value of newNotes.

Finally, regardless of whether we're editing or adding a note, it clears the newNotes field, likely resetting an input field or text area where users input their note content.

This function assumes that notesList, editedNoteId, newNotes, setNotesList, setEditedNoteId, and setNewNotes are all state variables and their corresponding setter functions from React's state management system, like useState.

Adding Edit Functionality

const onEdit = (id: number) => {
  // Find the note in notesList with the specified ID
  const note = notesList.find((note) => note.id === id);
 
  // If a note with the specified ID is found
  if (note) {
    // Set the value of newNotes to the title of the found note
    setNewNotes(note.title);
    // Set the value of editedNoteId to the ID of the found note
    setEditedNoteId(id);
  }
};

The function onEdit takes an id parameter, presumably representing the ID of the note to be edited.

It uses the Array.find() method to search through the notesList array to find the note with the specified ID. If a note with that ID is found, it will be stored in the note variable.

If note is not undefined (i.e., if a note with the specified ID is found), it sets the value of newNotes to the title of the found note. This likely updates the input field or text area where users input their note content with the current title of the note being edited.

It also sets the value of editedNoteId to the ID of the found note. This likely indicates to other parts of the application that a note is currently being edited and specifies which note it is.

Adding Delete Functionality

const onDelete = () => {
  // Filter out the note with the editedNoteId from the notesList
  const finalData: NotesI[] = notesList?.filter(
    (note: NotesI) => note.id !== editedNoteId
  );
  // Update notesList with the filtered data
  setNotesList(finalData);
  // Reset editedNoteId since the note is deleted
  setEditedNoteId(null);
  // Clear the newNotes field
  setNewNotes("");
};

The function onDelete is called when a user wants to delete a note.

It creates a new array finalData by filtering the notesList. It removes the note with the ID editedNoteId using the Array.filter() method. This creates a new array without the note to be deleted.

It then updates the notesList state variable with the new filtered array, effectively removing the note from the list.

It resets the editedNoteId state variable to null, indicating that no note is currently being edited.

Finally, it clears the newNotes field, likely resetting an input field or text area where users input their note content.

Final code

The final code for the App component with the edit and delete functionality added is as follows:

App.js
import { useState } from 'react';
import {
  SafeAreaView,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  ScrollView,
} from 'react-native';
import ListData from './src/list';
import { NotesI } from './src/types.d';
 
const App = () => {
  const [notesList, setNotesList] = useState<NotesI[]>([]);
  const [newNotes, setNewNotes] = useState<string>('');
  const [editedNoteId, setEditedNoteId] = useState<number | null>(null);
 
  const onHandlePress = () => {
    if (editedNoteId !== null) {
      setNotesList((prev) =>
        prev.map((note) => {
          if (note.id === editedNoteId) {
            return {
              ...note,
              title: newNotes,
            };
          }
          return note;
        })
      );
      setEditedNoteId(null);
    } else {
      setNotesList((prev) => [
        ...prev,
        {
          id: notesList.length + 1,
          title: newNotes,
        },
      ]);
    }
 
    setNewNotes('');
  };
 
  const onEdit = (id: number) => {
    const note = notesList.find((note) => note.id === id);
    if (note) {
      setNewNotes(note.title);
      setEditedNoteId(id);
    }
  };
 
  const onCancelEdit = () => {
    setNewNotes('');
    setEditedNoteId(null);
  };
 
  const onDelete = () => {
    const finalData: NotesI[] = notesList?.filter(
      (note: NotesI) => note.id !== editedNoteId
    );
    setNotesList(finalData);
    setEditedNoteId(null);
    setNewNotes('');
  };
 
  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.title}>Notes Application</Text>
      <TextInput
        onChangeText={setNewNotes}
        value={newNotes}
        placeholder="Enter the notes title"
        style={styles.input}
      />
      <TouchableOpacity
        disabled={!newNotes}
        style={styles.button}
        onPress={onHandlePress}>
        <Text style={styles.buttonText}>
          {editedNoteId !== null ? 'Save' : 'Add'} Notes
        </Text>
      </TouchableOpacity>
      {editedNoteId !== null && (
        <>
          <TouchableOpacity
            style={[styles.button, styles.cancelButton]}
            onPress={onDelete}>
            <Text style={styles.buttonText}>Delete Note</Text>
          </TouchableOpacity>
 
          <TouchableOpacity
            style={[styles.button, styles.cancelButton]}
            onPress={onCancelEdit}>
            <Text style={styles.buttonText}>Cancel Edit</Text>
          </TouchableOpacity>
        </>
      )}
      <Text style={styles.title}>Task List</Text>
      <ScrollView style={styles.scrollView}>
        <ListData data={notesList} onEdit={onEdit} />
      </ScrollView>
    </SafeAreaView>
  );
};
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginHorizontal: 20,
    marginTop: 40,
  },
  title: {
    textAlign: 'center',
    fontSize: 20,
    fontWeight: '600',
    color: 'blue',
    paddingVertical: 10,
  },
  input: {
    borderColor: 'gray',
    borderWidth: 2,
    borderRadius: 6,
    minHeight: 40,
    paddingLeft: 10,
    fontSize: 15,
    marginVertical: 10,
  },
  button: {
    backgroundColor: 'blue',
    paddingVertical: 10,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 6,
    marginBottom: 10,
  },
  cancelButton: {
    backgroundColor: 'red',
  },
  buttonText: { color: 'white' },
  scrollView: {
    marginTop: 5,
    marginBottom: 20,
  },
});
 
export default App;

In the code snippet above, we have added the functionality to edit notes. When a user clicks on the edit button,

list.js
import React from "react";
import {
  FlatList,
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
} from "react-native";
import { NotesI } from "./types.d";
 
const ListData = ({
  data,
  onEdit,
}: {
  data: NotesI[],
  onEdit: (id: number) => void,
}) => {
  if (!data || data.length <= 0) {
    return (
      <View>
        <Text style={styles.noData}>No data found :-)</Text>
      </View>
    );
  }
 
  const renderItem = ({ item }: { item: NotesI }) => (
    <TouchableOpacity style={styles.card} onLongPress={() => onEdit(item.id)}>
      <Text style={styles.cardText}>{item.title}</Text>
    </TouchableOpacity>
  );
 
  return (
    <View style={styles.container}>
      <FlatList
        data={data}
        renderItem={renderItem}
        keyExtractor={(item) => item.id.toString()}
      />
    </View>
  );
};
 
const styles = StyleSheet.create({
  container: { paddingVertical: 1 },
  card: {
    backgroundColor: "gray",
    paddingVertical: 10,
    borderRadius: 6,
    paddingHorizontal: 6,
    marginBottom: 10,
  },
  noData: {
    textAlign: "center",
  },
  cardText: { color: "white", fontSize: 16 },
});
export default React.memo(ListData);

In the code snippet above, we have added the functionality to edit notes. When a user clicks on the edit button, the note title is displayed in the input field, allowing the user to make changes. The user can then save the changes by clicking the "Save" button or cancel the edit by clicking the "Cancel Edit" button. The user can also delete the note by clicking the "Delete Note" button.

The onEdit function is called when the user long-presses on a note in the list. It retrieves the note's ID and sets the newNotes state variable to the note's title, allowing the user to edit the note. The onCancelEdit function is called when the user clicks the "Cancel Edit" button, resetting the newNotes and editedNoteId state variables.

The onDelete function is called when the user clicks the "Delete Note" button. It filters out the note with the editedNoteId from the notesList array and updates the list accordingly.

With these additions, users can now edit and delete notes in the application, enhancing the overall user experience.

Conclusion

In this tutorial, we continued building the notes application in React Native by adding the functionality to edit and delete notes. Users can now seamlessly manage their notes by editing the content of existing notes and deleting notes they no longer need. These features enhance the usability of the application and provide users with a more intuitive and efficient note-taking experience.