Your first Django app with ReactJs frontend
Published: 2024-02-15 17:51:41

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.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1708018681029/9e5875f2-21c7-4168-bd82-c394c98e3c72.png)

Open a new terminal and navigate to the desktop.

Run this command,

`django-admin startproject myproject`

If you got this error:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1708018730452/df756177-2ea9-4b08-bf06-70384d64e593.png)

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`

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1708018819336/808317a0-7957-4d48-9dce-4afdb4d6593e.png)

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`](http://manage.py) `startapp myapi`

Your directory now looks like this:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1708018930561/3be3ebd1-d9bf-4b1c-a41c-166acf53d662.png)

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

Next, Open the [settings.py](http://settings.py) file inside the myproject directory and add the following lines of code:

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

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

CORS_ORIGIN_ALLOW_ALL = True
```

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](http://views.py) file inside the myapi directory and add the following lines of code:

```plaintext
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!'})
```

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

Add URLs :

Open the [urls.py](http://urls.py) inside the myproject directory and add these lines:

```plaintext
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'),
]
```

This code defines a new URL pattern that maps to the hello\_world function in [views.py](http://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:

```plaintext
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;
```

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:

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

export default App;
```

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`](http://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/](http://localhost:3000/). You should see the message **"Hello, world!"** displayed on the web page.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1708019319158/5812fb79-8170-479b-9d17-85429b631b49.png)