CodeBlanks Logo Icon CodeBlanks

Adding notes

Write the add note form.

The add note form

In this lesson we will build a form to take a new note from the user. We use two TextInputs: one for the title and one for the body. Each input is bound to a state with value and onChangeText.

We keep the form output in state: title and body. As the user types, the matching state updates. Then on a button press we add the new note with setNotes. This pattern is the standard form pattern you will meet in React Native screens; it is the standard way to take user data into state.

Practice Take a title with TextInput

Add two new states to the NotesApp component: title and body (start with empty string). Add a TextInput; bind it with value={title} and onChangeText={setTitle}. The component returns <Text>Notes</Text>.

Starter code

App.js
import { useState } from "react";
import { Text } from "react-native";

function NotesApp() {
  const [notes, setNotes] = useState([{ id: "1", title: "Shopping", body: "Milk, bread" }]);
  // Add two more states for title and body (start with empty string)
  // Import the text input component and add one; bind it to the title state

  return <Text>Notes</Text>;
}

Sample solution

App.js
import { useState } from "react";
import { Text, TextInput } from "react-native";

function NotesApp() {
  const [notes, setNotes] = useState([{ id: "1", title: "Shopping", body: "Milk, bread" }]);
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");
  return (
    <>
      <TextInput value={title} onChangeText={setTitle} />
      <Text>Notes</Text>
    </>
  );
}

Form submission

When the user writes a note and submits, you need to add the new note to state. With the setNotes([...notes, newNote]) pattern you append the new note to the existing list. The new note's id must be unique; Date.now().toString() is a common choice.

After adding, you clear the form: with setTitle("") and setBody("") you empty the title and body states. This lets the user write the next note on a clean form. Form submission is usually wired to a button's onPress; when the button is pressed the add function runs.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Add a new note

Question
setNotes([...notes, { id: Date.now().toString(), ____: title, body }]);
Answer
setNotes([...notes, { id: Date.now().toString(), title: title, body }]);

Explanation: answer: title. The new note's title comes from the title state.

2 What do you use to add a new note?

App.js
setNotes(/* ? */);
  • setNotes([...notes, newNote]) Correct answer
  • notes = notes.concat(newNote)
  • setNotes(notes + newNote)
  • notes.push(newNote)

Explanation: setNotes([...notes, newNote]) creates a new array.

3 Match each piece to its role

Term Meaning
TextInput Title input
setTitle Updates title
setNotes Updates notes
Date.now() Generates a unique id

All lessons in Intermediate