Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 71 ยท Projects

Project: Blog App and Text Editor

Build a React Native blog app with create, read, update and delete, then a text editor with a formatting toolbar that works on the selected text, using testable pure functions.

A blog app is the classic CRUD project: Create, Read, Update and Delete posts. It is a good place to practice the structure of a multi-screen app (a list, a detail screen and a form that serves two purposes). A text editor is the next step: the user selects some words, taps Bold, and those words change. The trick of the editor is that formatting is just a transformation of a string given a selection, which makes it easy to write as a pure function and test.

What runs on this site. React Navigation, TextInput selection and WebView-based rich-text libraries need a native runtime, so their code is read-only. The post functions and the formatting functions are real runnable JavaScript, and the demos use stand-in screens built with HTML.

Part 1: the blog app

Data and screens

A post is a small object:

JavaScript
{ id: 'p1', title: 'Hello', body: 'First post', author: 'Ada', createdAt: 1700000000000, updatedAt: 1700000000000 }

The app has three screens:

Screen Job
Posts a FlatList of posts, newest first, a button to add a post
Post detail the full text, with Edit and Delete buttons
Post form the same form for a new post (no id) and an existing one (with id)

One form for creating and editing is a big saving: it takes an optional postId route param, loads the post if there is one, and calls savePost either way (see Passing Data Between Screens). A stack navigator connects them (see Stack Navigation).

The store as pure functions

As in the notes app, put the rules in plain functions and keep the screens thin:

JavaScript
export const newId = () => 'p' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);

export function validatePost({ title, body }) {
  const errors = {};
  if (!title.trim()) errors.title = 'A title is required.';
  else if (title.trim().length > 80) errors.title = 'Keep the title under 80 characters.';
  if (body.trim().length < 10) errors.body = 'Write at least 10 characters.';
  return errors;
}

export function savePost(posts, draft, now) {
  const clean = { ...draft, title: draft.title.trim(), body: draft.body.trim() };
  if (draft.id && posts.some((p) => p.id === draft.id)) {
    return posts.map((p) => (p.id === draft.id ? { ...p, ...clean, updatedAt: now } : p));   // update
  }
  return [{ ...clean, id: newId(), createdAt: now, updatedAt: now }, ...posts];              // create
}

export const deletePost = (posts, id) => posts.filter((p) => p.id !== id);
export const sortedNewestFirst = (posts) => [...posts].sort((a, b) => b.createdAt - a.createdAt);

Each function returns a new array and never mutates the old one, which React needs to notice the change. savePost keeps createdAt on edit and updates only updatedAt.

The screens

The posts list shows a title, an author, a snippet (the first line of the body, cut to about 100 characters) and a date. Tapping a row navigates to the detail screen with the post's id (not the whole object: the detail screen reads the current data from the store, so it always shows the latest edit).

JSX
function PostsScreen({ navigation }) {
  const { posts } = usePosts();
  return (
    <FlatList
      data={sortedNewestFirst(posts)}
      keyExtractor={(p) => p.id}
      ListEmptyComponent={<Text>No posts yet. Write the first one.</Text>}
      renderItem={({ item }) => (
        <Pressable onPress={() => navigation.navigate('Post', { id: item.id })} accessibilityRole="button">
          <Text style={styles.title}>{item.title}</Text>
          <Text numberOfLines={2}>{item.body}</Text>
        </Pressable>
      )}
    />
  );
}

Deleting is destructive, so confirm it with Alert.alert('Delete post?', 'This cannot be undone.', [{ text: 'Cancel', style: 'cancel' }, { text: 'Delete', style: 'destructive', onPress: remove }]) (see Modals, Alerts and Sheets) and navigate back after the delete. The same store can persist to AsyncStorage or send each change to a server, as in the notes app.

Blog CRUD logic with validation (stand-in screens)

Try saving an empty form (validation errors appear and nothing is saved), editing a post (its createdAt stays, updatedAt changes) and deleting one.

Part 2: a text editor with a toolbar

Selection and formatting

A TextInput reports the selection through onSelectionChange: event.nativeEvent.selection is { start, end }. Formatting is a function from (text, selection) to a new (text, selection). We use a lightweight Markdown-like syntax: **bold**, _italic_ and # Heading.

JavaScript
// Wrap the selection in a marker, or remove the marker if it is already wrapped.
export function toggleWrap(text, { start, end }, marker) {
  const before = text.slice(0, start);
  const chosen = text.slice(start, end);
  const after = text.slice(end);
  const m = marker.length;

  if (before.endsWith(marker) && after.startsWith(marker)) {            // already wrapped: unwrap
    return { text: before.slice(0, -m) + chosen + after.slice(m), selection: { start: start - m, end: end - m } };
  }
  return { text: before + marker + chosen + marker + after, selection: { start: start + m, end: end + m } };   // wrap
}

// Make the line that holds the cursor a heading (toggle "# ").
export function toggleHeading(text, { start }) {
  const lineStart = text.lastIndexOf('\n', start - 1) + 1;
  const hasMark = text.startsWith('# ', lineStart);
  const next = hasMark ? text.slice(0, lineStart) + text.slice(lineStart + 2) : text.slice(0, lineStart) + '# ' + text.slice(lineStart);
  const shift = hasMark ? -2 : 2;
  return { text: next, selection: { start: start + shift, end: start + shift } };
}

Each button calls one of these, sets the new text, and then sets the new selection so the highlighted words stay highlighted. In React Native you pass the selection back with the selection prop of TextInput:

JSX
const [text, setText] = useState('');
const [selection, setSelection] = useState({ start: 0, end: 0 });

<TextInput
  multiline
  value={text}
  onChangeText={setText}
  selection={selection}
  onSelectionChange={(e) => setSelection(e.nativeEvent.selection)}
/>
<Pressable onPress={() => { const r = toggleWrap(text, selection, '**'); setText(r.text); setSelection(r.selection); }}>
  <Text>B</Text>
</Pressable>

A caveat: with a controlled selection prop, a slightly late update can make the cursor jump on some devices. Many apps therefore control selection only for the moment after a toolbar action and leave it uncontrolled the rest of the time.

The preview

To show the formatted result, convert the Markdown-like text to React elements, never to an HTML string. React Native has no HTML, and escaping is automatic when you render text as children. A small parser splits each line into blocks and each block into bold and italic runs:

JavaScript
export function parseInline(line) {
  const parts = [];
  const re = /\*\*(.+?)\*\*|_(.+?)_/g;
  let last = 0, m;
  while ((m = re.exec(line))) {
    if (m.index > last) parts.push({ text: line.slice(last, m.index) });
    parts.push(m[1] !== undefined ? { text: m[1], bold: true } : { text: m[2], italic: true });
    last = re.lastIndex;
  }
  if (last < line.length) parts.push({ text: line.slice(last) });
  return parts;
}

Then a Preview component maps each line: a line starting with # becomes a Text with a bigger fontSize, others a paragraph; each part becomes a nested <Text style={{ fontWeight: part.bold ? '700' : '400', fontStyle: part.italic ? 'italic' : 'normal' }}> (nested text inherits the parent style, see Core Components).

Using a rich-text library

For real rich text (colours, lists, links, images) most apps use a library. react-native-pell-rich-editor renders an HTML editor in a WebView with a RichToolbar; Expo apps can also use @10play/tentap-editor. The library gives you HTML output, which you must sanitize before rendering it anywhere (see Security in Mobile Apps), and which you store as a string like any other body. If you only need bold, italic and headings, the small custom editor above is lighter, easier to test and has no WebView.

Selection-based formatting with a live preview

Select a word in the box and press B: the asterisks appear around it and the preview shows it bold; select it again and press B and it unwraps. The checks confirm the same behavior on plain strings. A user typing <b>hello</b> sees those characters, because the preview renders text, not markup.

Ideas to extend

  • Persist posts with AsyncStorage or send them to a server (see Networking with fetch).
  • Add comments, likes and pull to refresh on the list (see SectionList and Pull to Refresh).
  • Add a draft autosave that stores the form text after 500 ms of inactivity.
  • Support lists (- item) and links in the preview parser.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does one form screen serve both creating and editing a post?

    The same fields and validation apply to both cases. The id decides whether savePost updates or creates.
  2. 2. When a post is edited, which fields does savePost change?

    createdAt records when the post was written and must not change. updatedAt records the edit.
  3. 3. What does the selection object from onSelectionChange contain?

    selection is { start, end }. The text is obtained with text.slice(start, end).
  4. 4. Why does the preview render parsed parts as React elements instead of building an HTML string?

    Text rendered as children is treated as plain text, so a user's markup cannot run. It is also the only way to draw on native views.

Summary

  • A blog is CRUD: pure functions for validate, save, delete and sort; a list, a detail and a shared create-or-edit form; confirm destructive actions.
  • Keep createdAt stable and update updatedAt on edit; navigate with ids, not whole objects.
  • A formatting toolbar is a pure function from text and selection to new text and selection; restore the selection after the change.
  • Render a preview as React elements, never as unescaped HTML; use a rich-text library for complex formatting and sanitize its HTML.

Next: Practice Exercises (Basic).