Site icon Next.js & React.js Revolution | Your Daily Web Dev Insight

How to connect Django with React.js

Django with React.js

In the realm of web development, pairing Django with React.js is a formidable combination that offers the best of both worlds. Django, a robust Python-based web framework, serves as the backend powerhouse, while React.js brings life to the front end with its dynamic and responsive capabilities. This guide will walk you through the process of connecting Django with React.js, resulting in a feature-rich and seamlessly integrated web application.

The Power of React.js

React.js, also known as React, is a JavaScript library developed and maintained by Facebook. It has taken the web development world by storm, thanks to its component-based architecture, which simplifies the construction of intricate user interfaces. Here’s why React.js is a prominent choice for front-end development

The Versatility of Django

Django is a high-level Python web framework that has set the gold standard for back-end development. It offers an array of advantages that make it a top choice for building the server-side of your application

Bridging the Gap: Django with React.js

The pairing of Django with React.js offers a wealth of benefits. Here are some compelling reasons to choose this combination for your web development journey

Related: How to add theme to your React App

Connecting Django with React.js

Step 1: Setting Up the Backend with Django

In this step, you’ll create the Django backend for your application and set up the development server.

Create a Django Project

Open your terminal and navigate to the directory where you want to create your Django project. Run the following command, replacing ‘projectname‘ with your desired project name

django-admin startproject projectname

This command initializes a Django project with the specified name.

Run the Development Server

Navigate to the newly created project directory

cd projectname

Start the Django development server

python manage.py runserver

This command launches the development server, and your Django application should now be accessible at http://localhost:8000.

Step 2: Creating the Frontend with React.js

Now, let’s create the React.js frontend within your Django project.

Create a React App

While inside your Django project directory, use Create React App to generate a new React.js app named ‘frontend

npx create-react-app frontend

This command sets up the React.js project within your Django project directory.

Start the React Development Server

Change your current working directory to the ‘frontend’ folder

cd frontend

Initiate the React development server

npm start

The React app will start and be accessible at http://localhost:3000.

Step 3: Integrating the Frontend with Django

In this crucial step, you’ll ensure that the React.js frontend and Django backend communicate seamlessly.

Configure CORS (Cross-Origin Resource Sharing)


CORS allows your React front end, hosted on a different domain (typically http://localhost:3000), to interact with your Django back end (http://localhost:8000).

Install the “django-cors-headers” package
pip install django-cors-headers
Add ‘corsheaders’ to the INSTALLED_APPS list in your Django project’s settings (typically found in settings.py)
INSTALLED_APPS = [
    # ...
    'corsheaders',
]
Configure CORS by adding the following settings to your Django project’s settings
MIDDLEWARE = [
    # ...
    'corsheaders.middleware.CorsMiddleware',
]

CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",  # Allow requests from your React app
]

API Endpoints in Django


Create API endpoints in your Django project to serve data to the React front end. This involves defining Django views and setting up URL patterns.

In your Django ‘views.py‘, create a simple view that returns JSON data

from django.http import JsonResponse

def get_data(request):
    data = {'message': 'This is data from Django.'}
    return JsonResponse(data)

In your Django ‘urls.py’, set up a URL pattern to route requests to this view

from django.urls import path
from . import views

urlpatterns = [
    path('api/data/', views.get_data, name='get_data'),
]

Fetching Data in React


In your React components, you can fetch data from your Django back end using the ‘fetch‘ API or a library like Axios. For example, you can create a component that fetches data from your Django API endpoint

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

function DataFetchingComponent() {
    const [data, setData] = useState('');

    useEffect(() => {
        fetch('http://localhost:8000/api/data/')
            .then((response) => response.json())
            .then((data) => setData(data.message))
            .catch((error) => console.error(error));
    }, []);

    return (
        <div>
            <p>Data from Django: {data}</p>
        </div>
    );
}

export default DataFetchingComponent;

This completes the integration process, allowing your React.js front end to communicate with your Django back end. You now have the foundation for building a web application that combines the strengths of both technologies, creating a dynamic and interactive user experience.

Also Read: Create an App with React.js at the Front-end and Node.js at the Back-end

Step 4: Further Development and Deployment

Now that you’ve successfully connected Django with React.js, you can continue to develop your application. Add more views, models, and templates to your Django project, and enhance t e user interface and interactivity in your React.js front-end. Here’s how you can do that

Adding a New Django View and URL Mapping

You can add new views to your Django project for handling different functionalities. For example, let’s create a view to display a list of items from a database model.

# views.py

from django.shortcuts import render
from .models import Item

def item_list(request):
    items = Item.objects.all()
    return render(request, 'items/item_list.html', {'items': items})

Don’t forget to create a corresponding URL pattern in your Django ‘urls.py’

# urls.py

from django.urls import path
from . import views

urlpatterns = [
    # Your existing URL patterns
    path('items/', views.item_list, name='item_list'),
]

Fetching and Displaying Data in React

In your React.js front end, you can create components to fetch and display data from the Django back end. For example, you can create a component that lists items fetched from the Django API

// ItemList.js

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

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

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

    return (
        <div>
            <h2>Item List</h2>
            <ul>
                {items.map((item) => (
                    <li key={item.id}>{item.name}</li>
                ))}
            </ul>
        </div>
    );
}

export default ItemList;

Deployment

When you’re ready to deploy your application, you have several options. Here are steps for deploying your Django back end and React front end separately on Heroku and Netlify

Deploying Django on Heroku

Sign up for a Heroku account and install the Heroku CLI

Create a Procfile in your Django project’s root directory with the following content

web: python manage.py runserver 0.0.0.0:$PORT

Initialize a Git repository and commit your code

git init
git add .
git commit -m "Initial commit"

Create a Heroku app and push your code to Heroku

heroku create
git push heroku master

Migrate your database on Heroku

heroku run python manage.py migrate
Deploying React on Netlify

Sign up for a Netlify account and install the Netlify CLI.

Navigate to your React front-end project directory and build the project

Deploy the project to Netlify

npm run build

Follow the prompts and set up your deployment settings.

netlify deploy

The deployed React app will be accessible via the provided Netlify URL.

These steps will allow you to continue enhancing and deploying your Django and React.js application, whether you’re adding new features to the back end or improving the user interface on the front end. Enjoy developing and deploying your web application!

Conclusion

In the world of web development, connecting Django with React.js brings a powerful synergy. Django takes care of the server-side complexity, while React.js crafts engaging and responsive user interfaces. This combination enables you to build a wide range of web applications, from simple prototypes to complex, data-driven platforms. So, embark on your Django-React.js journey and create applications that stand out in today’s competitive web development landscape. Happy coding!

Looking to transform these insights into impactful results? Click here to unlock a new realm of possibilities. Your journey towards innovation begins with a single Click.

Exit mobile version