DEV Community

angela300
angela300

Posted on

Your first Django app with ReactJs frontend

ReactJS is a popular JavaScript library used for building user interfaces, and Django is a high-level Python web framework that is widely used for building web applications. Connecting these two powerful tools can produce a robust web application.

In this tutorial, we will learn how to connect ReactJS and Django Framework using A Hello World! application.

Make sure you already have Node.js and Python installed on your system

On your vs code terminal, open a new window.

Open a new terminal and navigate to the desktop.

Run this command,

django-admin startproject myproject

If you got this error:

Activate Virtual Environment (if applicable). If you're working within a virtual environment, make sure it's activated. You can activate it by running:

pipenv shell

After the error is solved, now run:

django-admin startproject myproject

This will create a new directory called myproject which will have the basic structure of a Django project.

Create a new React application in the myproject directory using the following command:

npx create-react-app myapp

Install Required Packages

Once the project and application are created, we need to install some packages. For Django,  install Django Rest Framework and Django Cors Headers. For React, install Axios for making HTTP requests.

To install Django Rest Framework and Django Cors Headers, run the following command in the myproject directory:

pip install djangorestframework django-cors-headers

To install Axios, run the following command inside the myapp directory:

npm install axios

Build the API Endpoints in Django

After installing the required packages, we can start building the API endpoints in Django. Create a new Django app to handle the API requests. The API endpoint will return JSON data when we make HTTP requests to it. We can use Django Rest Framework to build the API endpoints.

To create a new Django app, run the following command inside the myproject directory:

python manage.py startapp myapi

Your directory now looks like this:

The new directory called myapi has the basic structure of a Django app.

Next, Open the settings.py file inside the myproject directory and add the following lines of code:

INSTALLED_APPS = [
    'rest_framework',
    'corsheaders',
    'myapi',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True
Enter fullscreen mode Exit fullscreen mode

These lines of code will add the rest_framework, corsheaders, and myapi apps to the INSTALLED_APPS list, add the CorsMiddleware to the MIDDLEWARE list, and allow all origins to make cross-origin requests.

When we try to make an HTTP request from a different origin (e.g., from the React app to the Django API), we may run into a CORS error. To fix this, we need to add the Django Cors Headers package to the Django project. This package will add the necessary headers to allow cross-origin requests.

Next, open the views.py file inside the myapi directory and add the following lines of code:

from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET'])
def hello_world(request):
    return Response({'message': 'Hello, world!'})
Enter fullscreen mode Exit fullscreen mode

This code defines a new API endpoint that returns a JSON response with the message “Hello, world!”.

Add URLs :

Open the urls.py inside the myproject directory and add these lines:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('myapi.urls'))
]
Finally, Create the urls.py file inside the myapi directory and add the following lines of code:
from django.urls import path
from . import views

urlpatterns = [
    path('hello-world/', views.hello_world, name='hello_world'),
]
Enter fullscreen mode Exit fullscreen mode

This code defines a new URL pattern that maps to the hello_world function in views.py.

Next, We  will create a React component that makes HTTP requests to the API endpoints. We will use Axios to make the HTTP requests. Once we receive the JSON data, we can display it on the web page using React components.

Create a new file called HelloWorld.js inside the src directory of the myapp directory, and add the following lines of code:

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

function HelloWorld() {
  const [message, setMessage] = useState('');

  useEffect(() => {
    axios.get('http://localhost:8000/hello-world/')
      .then(response => {
        setMessage(response.data.message);
      })
      .catch(error => {
        console.log(error);
      });
  }, []);

  return (
    <div>
      <h1>Hello, World!</h1>
      <p>{message}</p>
    </div>
  );
}

export default HelloWorld;
Enter fullscreen mode Exit fullscreen mode

This code defines a new React component called HelloWorld that makes an HTTP GET request to the hello-world API endpoint we defined earlier. The response data is stored in the message state, which is displayed on the web page.

Finally, we will now render the HelloWorld component inside the App.js file in the src directory of the myapp directory. Replace the contents of App.js with the following lines of code:

function App() {
  return (
    <div>
      <HelloWorld />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

This code renders the HelloWorld component inside the div element with the root ID.

To run the project, open two terminal windows.

In the first window, navigate to the myproject directory and run the following command:

python manage.py runserver

This will start the Django development server.

In the second window, navigate to the myapp directory and run the following command:

npm start

This will start the React development server.

Open your web browser and navigate to http://localhost:3000/. You should see the message "Hello, world!" displayed on the web page.

Top comments (0)