How To Use React JS with Django

Udemezue John - Oct 6 - - Dev Community

Introduction.

Building web applications that are both powerful and user-friendly requires a solid understanding of modern technologies. One popular combination is React.js for the front end and Django for the back end.

React.js, a JavaScript library developed by Facebook, is known for its efficiency in creating dynamic user interfaces.

According to the 2023 Stack Overflow Developer Survey, 40% of developers reported using React, making it one of the most loved frameworks out there.

On the other hand, Django, a high-level Python web framework, simplifies the development of secure and maintainable web applications.

Its emphasis on rapid development and clean, pragmatic design has made it a favourite among developers, especially for projects requiring a robust back end.

Integrating these two powerful tools opens up a world of possibilities. The seamless communication between Django's RESTful API and React's dynamic UI capabilities allows for the creation of highly interactive applications.

In this guide, I’ll walk you through the essential steps to effectively use React.js with Django.

Why Combine React and Django?

Before diving into the implementation, it’s worth exploring why one might choose to use React with Django.

  • Separation of Concerns: By using React for the frontend and Django for the backend, I can create a clean separation between the user interface and the server-side logic. This separation makes it easier to manage and develop both parts of the application independently.
  • Performance: React is designed for high performance with its virtual DOM, allowing for efficient updates and rendering. This can significantly enhance the user experience compared to traditional server-rendered applications.
  • RESTful API: Django Rest Framework (DRF) makes it simple to create RESTful APIs that can be consumed by React. This allows for smooth data fetching and manipulation.
  • Rapid Development: Django's built-in features, like an ORM and an admin panel, accelerate backend development. Coupled with React's component-based architecture, I can quickly build full-featured applications.

How Do I Use React JS with Django?

Combining React.js with Django can lead to the creation of powerful web applications that benefit from both a robust backend and a dynamic frontend.

React.js, a popular JavaScript library for building user interfaces, is perfect for creating engaging and interactive applications.

Meanwhile, Django, a high-level Python web framework, excels at building secure and scalable backends.

In this article, I’ll walk through how to set up a project using Django as the backend API and React.js as the frontend, covering everything from installation to creating a basic application.

Setting Up the Environment

To get started, I’ll need to set up my development environment. Here’s a step-by-step guide:

1. Install Python and Django

First, ensure Python is installed on your machine. You can download it from Python's official website.

Once Python is installed, I can set up a virtual environment and install Django.



# Create a virtual environment
python -m venv myenv
cd myenv
source bin/activate  # On Windows use myenv\Scripts\activate

# Install Django
pip install django



Enter fullscreen mode Exit fullscreen mode

2. Create a Django Project.

Now, let’s create a Django project and an app within it.



django-admin startproject myproject
cd myproject
django-admin startapp myapp



Enter fullscreen mode Exit fullscreen mode

3. Install Django Rest Framework.

I’ll install the Django Rest Framework to help create the API.



pip install djangorestframework



Enter fullscreen mode Exit fullscreen mode

4. Configure Django Settings.

Next, I need to add the installed app and the REST framework to the Django settings. Open myproject/settings.py and add:



INSTALLED_APPS = [
    ...,
    'rest_framework',
    'myapp',
]



Enter fullscreen mode Exit fullscreen mode

5. Set Up the API.

Now, let’s create a simple API endpoint in Django. In myapp/models.py, I’ll create a model.



from django.db import models

class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()



Enter fullscreen mode Exit fullscreen mode

I’ll then create a serializer in myapp/serializers.py.



from rest_framework import serializers
from .models import Item

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = '__all__'



Enter fullscreen mode Exit fullscreen mode

Next, in myapp/views.py, I’ll create a view for the API:



from rest_framework import viewsets
from .models import Item
from .serializers import ItemSerializer

class ItemViewSet(viewsets.ModelViewSet):
    queryset = Item.objects.all()
    serializer_class = ItemSerializer



Enter fullscreen mode Exit fullscreen mode

Lastly, I need to set up the URLs in myapp/urls.py.



from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import ItemViewSet

router = DefaultRouter()
router.register(r'items', ItemViewSet)

urlpatterns = [
    path('', include(router.urls)),
]



Enter fullscreen mode Exit fullscreen mode

And include these URLs in the main urls.py:



from django.contrib import admin
from django.urls import path, include

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



Enter fullscreen mode Exit fullscreen mode

6. Migrate the Database.

After setting up the model, I’ll run the following commands to create the database tables.



python manage.py makemigrations
python manage.py migrate



Enter fullscreen mode Exit fullscreen mode

7. Run the Django Server.

I can now run the Django server and check the API endpoint.



python manage.py runserver



Enter fullscreen mode Exit fullscreen mode

I’ll visit http://localhost:8000/api/items/ in the browser to see my API in action.

Setting Up the React Frontend.

1. Create a React App

With the Django API ready, it’s time to set up the React frontend. I’ll use create-react-app to bootstrap a new React application.



npx create-react-app myfrontend
cd myfrontend


Enter fullscreen mode Exit fullscreen mode

2. Install Axios.

I’ll install Axios to handle HTTP requests to the Django API.



npm install axios



Enter fullscreen mode Exit fullscreen mode

3. Fetch Data from the API.

Now, I can create a component that fetches data from the Django API. In src/App.js, I’ll add the following code:



import React, { useEffect, useState } from 'react';
import axios from 'axios';

function App() {
    const [items, setItems] = useState([]);

    useEffect(() => {
        axios.get('http://localhost:8000/api/items/')
            .then(response => {
                setItems(response.data);
            })
            .catch(error => {
                console.error('Error fetching data:', error);
            });
    }, []);

    return (
        <div>
            <h1>Items</h1>
            <ul>
                {items.map(item => (
                    <li key={item.id}>{item.name}: {item.description}</li>
                ))}
            </ul>
        </div>
    );
}

export default App;



Enter fullscreen mode Exit fullscreen mode

4. Run the React App.

To run the React app, I can use the following command:



npm start



Enter fullscreen mode Exit fullscreen mode

Now, visiting http://localhost:3000/ should display the list of items fetched from the Django API.

Cross-Origin Resource Sharing (CORS)
Since my React frontend and Django backend run on different ports, I need to configure CORS. I’ll install django-cors-headers.



pip install django-cors-headers



Enter fullscreen mode Exit fullscreen mode

Next, I’ll add it to INSTALLED_APPS and configure it in settings.py:



INSTALLED_APPS = [
...,
'corsheaders',
]

MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
...
]

CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
]

Enter fullscreen mode Exit fullscreen mode




Conclusion.

By following these steps, I’ve successfully set up a React frontend that communicates with a Django backend through a RESTful API. This setup allows me to leverage the strengths of both technologies to build a modern web application.

As I continue to develop my application, I can add more features, handle user authentication, and improve the user interface with advanced React components.

Combining React with Django opens up a world of possibilities for building efficient and scalable web applications.

. . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player