Building a Web App using React & Django
Tags: react, javascript, django, python
Published: 2024-01-01 22:45:06

Hi Devs!

Happy New Year!!
2 years back, when I initially started with Django, all the resources I followed mostly suggested using HTML & CSS Templating. But I always wanted to use React for my Front-end. Again, finding a resource to learn about it was a pain. However, I found a few which were quite difficult to understand initially.

Eventually, it was easy to understand once I understood the Flow of Interaction between my Frontend and Backend. Building a web application using React for the frontend and Django for the backend, the communication between the two involves several components, including Axios for handling HTTP requests, URLs for routing, serializers for data conversion, and views for handling requests on the Django side. Here's a high-level overview of how these components interact:
<br/>
## React Frontend

![ReactJS Logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/whjzwlari1r5v96mi8ri.jpeg)

React is a JavaScript library for building user interfaces, and it typically runs in the browser. In the context of a web application, React is responsible for creating the user interface components, handling user interactions, and managing the application state.
<br/>
## Axios for HTTP Requests

![Axios Logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/njsi3njurnsgj1lx8jmz.png)
Axios is a popular JavaScript library for making HTTP requests from the browser. In a React application, Axios is commonly used to send requests to the Django backend to fetch or send data. Perfect for our React app to communicate with the Django backend.
<br/>
## URLs for Routing
In Django, the `urls.py` file is used to define URL patterns and their corresponding views. These URL patterns determine how requests are routed to different views within the Django backend.

```python
from django.urls import path
from . import views

urlpatterns = [
    path('list/', views.read_all_data, name='read_data'),
    # Other URL Patterns
]
```
_This is an example of `urls.py` in Django_
<br/>
## Serializers for Data Conversion
Serializers in Django are used to convert complex data types (e.g., Django models) to native Python data types, and vice versa.
They are particularly useful when sending data between the frontend and backend in JSON format.

```python
from rest_framework import serializers
from .models import MyModel

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = '__all__'
```
_This is an example of `serializers.py` in Django_
<br/>
## Database Interactions
Django models define the database structure, and ORM (Object-Relational Mapping) simplifies database operations.
```python
from django.db import models

class MyModel(models.Model):
    # Define the model fields here
```
_This is an example of `models.py` in Django_
<br/>
## Views for Request Handling
Django views process incoming requests, interact with models and serializers, and return appropriate responses.

```python
@api_view(['GET'])
def api_data_view(request):
    data = MyModel.objects.all()
    serializer = MyModelSerializer(data, many=True)
    return Response(serializer.data)
```
_This is a code snippet example of `views.py` in Django_
<br/>
## Fetching Data
Use Axios in a React component to fetch data from Django, where the backend interacts with the database.

```javascript
const fetchData = async () => {
  try {
    const response = await axios.get('/list');
    console.log(response.data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};
```
_This is an example of using Axios in a React component_
<br/>

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2tier1eryahnu9jnduws.png)
By seamlessly integrating React and Django, including Axios, URLs, serializers, views, and database interactions, we've built a robust web application following RESTful principles.

The database plays a pivotal role in storing and retrieving data, enhancing the overall functionality of our application.