React + Django + Ninja (Full-stack in 15 mins) ⚛️🥷

Photo of Tom Dekan
by Tom Dekan

We'll create a full-stack web app using: - Django as the backend (using the neat Django Ninja library) - React as the frontend (using TypeScript)

Our aim: create an app that displays a list of trees fetched from a Django API. Very quickly.

Here's a video guide of me building this 🙂:


You can find the finished code for this tutorial on [GitHub](

Part 1: Setting up the Django Backend

Step 1: Create a Django Project

  1. Open a terminal and create a new directory for your project:
mkdir django-react-app
cd django-react-app
  1. Create a virtual environment and activate it:
python -m venv venv
source venv/bin/activate  # On Windows, use `venv\Scripts\activate`
  1. Install Django:
pip install django django-cors-headers django-ninja
  1. Create a new Django project:
django-admin startproject core .
  1. Create a new Django app:
python manage.py startapp sim

Step 2: Configure the Django Project

  1. Open core/settings.py and add 'sim' to the INSTALLED_APPS list:
INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'sim',  # Add this line
]
  1. In the same file, add CORS settings to allow requests from your React app:
INSTALLED_APPS = [
   # ... other apps ...
   'corsheaders',  # Add this line
   'sim',
]

MIDDLEWARE = [
   'corsheaders.middleware.CorsMiddleware',  # Add this line
   # ... other middleware ...
]

CORS_ALLOWED_ORIGINS = [
   "http://localhost:5173",  # Add this line (Vite's default port)
]

Step 3: Create the Tree Model

  1. Open sim/models.py and add the following code:
from django.db import models

class Tree(models.Model):
   name = models.CharField(max_length=255)

   def __str__(self):
      return self.name
  1. Create and apply migrations:
python manage.py makemigrations
python manage.py migrate

Step 4: Create the API

  1. Create a new file sim/api.py and add the following code:
from ninja import NinjaAPI
from .models import Tree

api = NinjaAPI()

@api.get("/trees")
def list_trees(request):
   trees = Tree.objects.all()
   return [{"id": tree.id, "name": tree.name} for tree in trees]
  1. Update sim/urls.py to include the API:
from django.urls import path
from .api import api


urlpatterns = [
   path('api/', api.urls),
]
  1. Update core/urls.py to include the sim app's URLs:
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
   path('admin/', admin.site.urls),
   path('', include('sim.urls')),
]

Step 5: Add Some Data

  1. Open the Django shell to add some trees:
python manage.py shell

Then:

from sim.models import Tree
Tree.objects.create(name="Oak")
Tree.objects.create(name="Pine")
Tree.objects.create(name="Maple")
Tree.objects.create(name="Birch")
Tree.objects.create(name="Willow")
  1. Run the development server:
python manage.py runserver
  1. Test the API by visiting http://localhost:8000/api/trees. You should see a JSON response with the trees you added.

Part 2: Setting up the React Frontend

Step 1: Create a Vite React Project

  1. In a new terminal (keep the Django server running), navigate to your project directory and create a new Vite project:
npm create vite@latest vite-project -- --template react-ts
cd vite-project
npm install

Step 2: Update the React App

  1. Replace the contents of src/App.tsx with the following:
import { useEffect, useState } from 'react';

function App() {
   interface Tree {
      id: number;
      name: string;
   }

    const [trees, setTrees] = useState<Tree[]>([]);

   const fetchTrees = async () => {
      const response = await fetch('http://localhost:8000/api/trees');
      const data = await response.json();
      setTrees(data);
   };

   useEffect(() => {
      fetchTrees();
   }, []);

   return (
           <>
              <div>List of trees</div>
              {trees.map((tree: Tree) => (
                      <div key={tree.id}>{tree.name}</div>
              ))}
           </>
   );
}

export default App;

Step 3: Run the React App

  1. Start the development server:
npm run dev
  1. Open http://localhost:5173 in your browser. You should see the list of trees you added in the Django admin.

Testing and Troubleshooting

  1. Django API:
  2. Ensure your Django server is running (python manage.py runserver).
  3. Visit http://localhost:8000/api/trees to verify the API is working.
  4. If you don't see any trees, make sure you've added some through the Django shell.

  5. React App:

  6. Check the browser console for any errors.
  7. If you see a CORS error, make sure you've properly configured CORS in your Django settings.
  8. Verify that the fetch URL in App.tsx matches your Django server's address and port.

  9. Data Flow:

  10. Use browser developer tools to inspect the network requests.
  11. Verify that the request to /api/trees is being made and returning the expected data.

  12. Component Rendering:

  13. Use React Developer Tools to inspect the component state and ensure the trees state is being updated correctly.

Remember to test your application thoroughly at each step. If you encounter any issues, double-check your code against the provided examples and ensure all necessary dependencies are installed.

Conclusion

You've now created a basic Django and React application that fetches and displays data from an API!

Let's get visual.

Do you want to create beautiful frontends effortlessly?
Click below to book your spot on our early access mailing list (as well as early adopter prices).
Copied link to clipboard 📋

Made with care by Tom Dekan

© 2024 Photon Designer