React Router V7 FullStack CRUD Tutorial | Learn Routing, Loaders, Actions...

PedroTechAbout 6 min readMay 27, 2025Watch original
THE SUMMARYAI-generated

Key Concepts

  • React Router v7 as a framework
  • CRUD operations (Create, Read, Update, Delete)
  • Dynamic routes
  • Data loaders (loaders)
  • Form actions (actions)
  • Superbase integration
  • Metadata management (meta function)
  • TypeScript usage
  • Tailwind CSS integration

React Router v7 Project Setup

  1. Project Creation:
    • Use the command npx create-react-router@latest to initialize a new React Router v7 project.
    • The command prompts for:
      • Project directory (use "." for the current directory).
      • Git repository initialization (recommended).
      • Dependency installation via npm (recommended).
    • The project is based on Vite, indicated by the npm run dev command starting the app on localhost:5173.
  2. Superbase Setup:
    • Create a Superbase account and a new project.
    • Name the project (e.g., "React Router CRUD").
    • Generate a database password.
    • Retrieve the Superbase URL and anonymous key from the project API settings.
  3. Superbase Client Configuration:
    • Create a SuperbaseClient.ts file.
    • Install the Superbase JavaScript library: npm install @superbase/supbase-js.
    • Import createClient from @superbase/supbase-js.
    • Define variables for superbaseURL and superbaseAnonKey using the values from Superbase.
    • Export a superbase client instance using createClient(superbaseURL, superbaseAnonKey).
    • Security Note: The video mentions the importance of using environment variables for Superbase keys in production to avoid exposing them.

Project Structure and Routing

  1. app Directory: Contains the core components and routes of the application.
  2. root.tsx: A special file that defines the overall layout of the application.
    • Includes:
      • Layout component: Defines the HTML structure, including meta information and links.
      • App component: Renders the Outlet, which displays the content of the current route.
      • ErrorBoundary: Handles errors.
  3. routes.ts: The central file for defining routes in React Router v7.
    • Routes are defined as an array of route objects.
    • index function: Defines the component for the root path ("/").
    • route function: Defines routes with a specific path and component.
  4. Creating Routes:
    • Create a new .tsx file in the routes directory for each route (e.g., items.tsx, new-item.tsx).
    • Export a default React component from each file.
    • In routes.ts, use the index or route functions to associate the path with the component.
    • Example:
      // routes.ts
      import { route } from '@tanstack/react-router';
      import Items from './routes/items';
      import NewItem from './routes/new-item';
      
      export const RouteTree = route({
        path: '/',
        children: [
          route({
            id: 'items',
            path: '/',
            component: Items,
          }),
          route({
            id: 'new-item',
            path: '/new',
            component: NewItem,
          }),
        ],
      });
      
  5. Navigation:
    • Use the NavLink component from React Router to create links between routes.
    • The to prop specifies the target path.
    • NavLink supports conditional styling based on the route's active state using the isActive boolean in the className function.

CRUD Implementation with Superbase

  1. Superbase Table Setup:
    • Create a table named "items" in Superbase.
    • Columns:
      • id (auto-generated)
      • title (text, not nullable)
      • description (text, nullable)
  2. Create (New Item Route):
    • UI: A form with input fields for "title" and "description," and a "Create Item" button.
    • Form Component: Use the Form component from React Router.
    • Action:
      • Define an action function (exported as action) to handle form submissions.
      • The action function receives a request argument of type ActionFunctionArgs.
      • Extract form data using await request.formData().
      • Get individual field values using formData.get('fieldName') and cast them to strings.
      • Validate input data.
      • Use the Superbase client to insert a new record into the "items" table.
      • Handle potential errors from Superbase.
      • Use the redirect function from React Router to navigate to the homepage after successful creation.
    • Metadata: Use the meta function to define the title and description for the "New Item" page.
  3. Read (Items Route):
    • Loader:
      • Define a loader function (exported as loader) to fetch data.
      • The loader function uses the Superbase client to select all records from the "items" table.
      • Handle potential errors from Superbase.
      • Return the fetched data as an object.
    • Component:
      • Access the data from the loader function using the useLoaderData hook.
      • Display the list of items in an unordered list (<ul>).
      • Each item is rendered as a link (<Link>) to its individual item page.
    • Metadata: Use the meta function to define the title and description for the "Items" page.
  4. Update/Delete (Item Route):
    • Dynamic Route: Define a route with a parameter for the item ID (e.g., /items/:id).
    • Loader:
      • The loader function receives a params object containing the item ID.
      • Use the Superbase client to select a single record from the "items" table based on the ID.
      • Handle potential errors from Superbase.
      • Return the fetched item data.
    • Component:
      • Access the item data using the useLoaderData hook.
      • Display a form with input fields pre-filled with the item data.
      • Include "Update" and "Delete" buttons.
    • Action:
      • The action function receives a request argument and a params object containing the item ID.
      • Determine the intent (update or delete) based on the value of the submitted button.
      • Update:
        • Use the Superbase client to update the record in the "items" table.
        • Handle potential errors from Superbase.
        • Return a success message or an error message.
      • Delete:
        • Use the Superbase client to delete the record from the "items" table.
        • Handle potential errors from Superbase.
        • Redirect to the homepage after successful deletion.
    • Metadata: Use the meta function to define the title and description for the "Item" page, including the item ID in the title.

Technical Terms and Concepts

  • CRUD: Create, Read, Update, Delete - basic database operations.
  • React Router v7: A routing library for React applications that allows you to create dynamic and complex user interfaces.
  • Superbase: An open-source Firebase alternative that provides a backend-as-a-service platform.
  • Vite: A fast build tool for modern web development.
  • Tailwind CSS: A utility-first CSS framework.
  • TypeScript: A superset of JavaScript that adds static typing.
  • JSX: A syntax extension to JavaScript that allows you to write HTML-like code in React components.
  • Components: Reusable building blocks of a React application.
  • Props: Data passed from a parent component to a child component.
  • State: Data that is managed within a component and can change over time.
  • Hooks: Functions that let you "hook into" React state and lifecycle features from function components.
  • Loader: A function that fetches data for a route.
  • Action: A function that handles form submissions and performs data mutations.
  • Metadata: Data about data, such as the title and description of a web page.
  • SEO: Search Engine Optimization - the process of improving the visibility of a website in search engine results pages.
  • Dynamic Routes: Routes that can change based on user input or other factors.
  • Params: Parameters passed in the URL of a dynamic route.
  • Form Data: Data submitted through an HTML form.
  • Environment Variables: Variables that are set in the environment in which a program is running.

Conclusion

This video provides a comprehensive guide to building a full-stack CRUD application using React Router v7 and Superbase. It covers project setup, routing, data fetching, form handling, and metadata management. The video emphasizes the importance of using React Router v7's features, such as loaders and actions, to create a well-structured and maintainable application. It also highlights the benefits of using TypeScript for type safety and Tailwind CSS for styling. The tutorial offers practical examples and step-by-step instructions, making it a valuable resource for developers looking to learn React Router v7.

AI summaries can miss context or contain errors. Check important details against the original video.

Go a little deeper.

Have a question about this video? Load its transcript to open the video chat.