ReactRealm

Setting Up Your Environment

  1. Create a New React AppUse Create React App to set up your project:bashCopy codenpx create-react-app react-realm cd react-realm
  2. Install RealmYou’ll need to install the Realm database package:bashCopy codenpm install realm

Step 2: Create the Realm Schema

First, we need to define our data model. Create a new file called Book.js in the src folder to define the Realm schema:

javascriptCopy code// src/Book.js
import Realm from 'realm';

class Book {
  static schema = {
    name: 'Book',
    properties: {
      id: 'int',
      title: 'string',
      author: 'string',
    },
    primaryKey: 'id',
  };
}

export default Book;

Step 3: Create Basic Components

We’ll create two main components: BookList and AddBook.

1. Create BookList.js

In the src folder, create a new file called BookList.js:

javascriptCopy code// src/BookList.js
import React from 'react';
import { View, Text, FlatList, StyleSheet, Button } from 'react-native';

const BookList = ({ books, onDelete }) => {
  return (
    <FlatList
      data={books}
      keyExtractor={(item) => item.id.toString()}
      renderItem={({ item }) => (
        <View style={styles.itemContainer}>
          <Text style={styles.itemText}>
            {item.title} by {item.author}
          </Text>
          <Button title="Delete" onPress={() => onDelete(item.id)} />
        </View>
      )}
    />
  );
};

const styles = StyleSheet.create({
  itemContainer: {
    padding: 15,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    borderBottomWidth: 1,
    borderBottomColor: '#ccc',
  },
  itemText: {
    fontSize: 18,
  },
});

export default BookList;

2. Create AddBook.js

Now create another file called AddBook.js:

javascriptCopy code// src/AddBook.js
import React, { useState } from 'react';
import { View, TextInput, Button, StyleSheet } from 'react-native';

const AddBook = ({ onAdd }) => {
  const [title, setTitle] = useState('');
  const [author, setAuthor] = useState('');

  const handleSubmit = () => {
    if (title && author) {
      onAdd({ title, author });
      setTitle('');
      setAuthor('');
    }
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="Book Title"
        value={title}
        onChangeText={setTitle}
      />
      <TextInput
        style={styles.input}
        placeholder="Author"
        value={author}
        onChangeText={setAuthor}
      />
      <Button title="Add Book" onPress={handleSubmit} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    marginBottom: 20,
  },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    padding: 10,
    marginBottom: 10,
  },
});

export default AddBook;

Step 4: Main Application Component

Now, let’s integrate everything in App.js.

javascriptCopy code// src/App.js
import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import Realm from 'realm';
import Book from './Book';
import BookList from './BookList';
import AddBook from './AddBook';

const App = () => {
  const [books, setBooks] = useState([]);
  const realm = new Realm({ schema: [Book] });

  useEffect(() => {
    const loadBooks = () => {
      const storedBooks = realm.objects('Book');
      setBooks(Array.from(storedBooks));
    };

    loadBooks();
  }, []);

  const addBook = ({ title, author }) => {
    realm.write(() => {
      const newBook = realm.create('Book', {
        id: realm.objects('Book').length + 1,
        title,
        author,
      });
      setBooks((prevBooks) => [...prevBooks, newBook]);
    });
  };

  const deleteBook = (id) => {
    realm.write(() => {
      const bookToDelete = realm.objectForPrimaryKey('Book', id);
      if (bookToDelete) {
        realm.delete(bookToDelete);
        setBooks((prevBooks) => prevBooks.filter((book) => book.id !== id));
      }
    });
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>ReactRealm: Book Manager</Text>
      <AddBook onAdd={addBook} />
      <BookList books={books} onDelete={deleteBook} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#fff',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
});

export default App;

Step 5: Run Your Application

Now you can start your application. In your terminal, run:

bashCopy codenpm start

This command will open a new tab in your browser, allowing you to run the app on an emulator or your physical device using Expo Go app.

Summary

In this tutorial, you created a simple book manager app using Realm for data persistence. You learned how to manage state, create reusable components, and interact with a local database.

Feel free to enhance the application with additional features, such as:

  • Editing book details
  • Searching for books
  • Adding categories or tags

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *