Integrating React in the Django way! with Jiten Sidhpura

This video features Jiten Sidhpura at DjangoCon US 2022 in San Diego, California, USA.

Integrating React in the Django way! with Jiten Sidhpura
0:19:16
Published November 16, 2022
1,063 views

Many times we would like to use React in our Django project to make highly interactive user interfaces. You don't want to isolate your frontend and backend, also configuring tools like Babel, Webpack, and Webpack Dev Server, deter you from using React in your project? Well, django-webpack-dev-server is a command-line reusable django package that installs the required dependencies and configures a React application in your project with just a single command.

This talk was presented at: https://2022.djangocon.us/talks/integrating-react-in-the-django-way/

LINKS:
Follow Jiten Sidhpura 👇
On Twitter: https://twitter.com/jiten_sid
On GitHub: https://github.com/jitensid
Website: https://www.linkedin.com/in/jiten-sidhpura/

Follow DjangCon US 👇
https://twitter.com/djangocon

Follow DEFNA 👇
https://twitter.com/defnado
https://www.defna.org/

Summary

React is useful for interactive interfaces whose state changes frequently, but it does not have to replace Django’s server-rendered pages. Jiten Sidhpura compares separating React and Django into independent projects with combining them in one Django project, arguing that the latter preserves Django forms and authentication, avoids CORS and a two-location deployment, and lets developers choose React only where it adds value. His Django Webpack DevServer package generates a React-enabled Django app, configures Webpack and Babel, supports hot reloading during development, and builds optimized production assets. A demonstrated to-do application uses Django forms for login and registration, React and React Bootstrap for the interactive home page, Axios for POST requests with CSRF tokens, and Django template data passed into React through a JSON script tag.

Key takeaways

  • Separate React and Django projects can suit larger teams, but require REST APIs, separate deployments, and additional authentication and CORS considerations.
  • A single Django project can serve both traditional templates and React-rendered pages, preserving Django forms and built-in authentication.
  • The Django Webpack DevServer package creates a configured React app with Webpack, Babel, templates, and the required Django integration steps.
  • Webpack DevServer provides hot reloading during development, while a production build minifies and optimizes the frontend assets.
  • Django data such as the logged-in username can be passed into React through a JSON script tag, and Axios requests must include Django’s CSRF token.
  • Using React only for complex interfaces and plain HTML, CSS, Bootstrap, or Django forms for simpler pages can reduce frontend bundle size and improve performance.

Summarised automatically from the transcript.

Transcript

2,811 words · auto-generated Show

Automatically transcribed, so expect mistakes in names and technical terms.

0:21

Hello everyone, I hope you are doing well. Welcome to DjangoCon US. So integrating React in the Django way In this talk, I'll be talking about how you can integrate React and Django together and I'll be talking about a Python package that I developed specifically for this purpose. The name of the Python package is Django Webpack DevServer. For this talk, I assume you have basic understanding of the Django framework. So before we begin this talk, uh little bit information about myself. My name is Jitane Sitpura and I completed my computer engineering just a couple of months back. So basically I am a fresher who just recently started his professional software development journey. Currently, I am working as a full-time software development engineer from Mumbai, India, and I have been using the Django framework from the past three years to develop various projects.

1:17

One thing I like to do is I find problems and then with the help of my programming skills I build solutions for it. And apart from that, in my free time I love to read books and go to beaches. So before we talk about integrating React in Django, let's first find out why you should use a front-end framework with Django in the first place. So for this consider websites like LinkedIn or Instagram. So these are popular social media websites and in these websites a user can perform many actions. A user can basically on these platforms can create a post, like, share, repost on other people's post, they can comment on other people's posts and they can reply to specific

2:03

comments on a post and they can also chat with the end users So we can see there is a lot of interactivity between the end user and the website. And as soon as a user performs an action, the UI of the web page gets updated. And we can see that in websites which are developed these days, there is a lot of interactive UI, and and they generally do this so that they can have a better user experience. and they which helps them to uh keep them engaged in their platforms. So and when such kind of UI if we try to develop with uh traditional uh techniques like using vanilla javascript or A jQuery library, then it might get difficult after a specific period of time.

2:50

And for this purpose, front-end frameworks come to your rescue. So they are basically designed With the intention to make the process of AI development much faster, cleaner, and easier. And there are many front-end frameworks out there. Some of the front-end frameworks are React Angular View So in this talk we will be focusing on React. So React is a JavaScript user interface library which is developed by Meta, previously known as Feed. Facebook and it has an awesome developer community and it has a rich ecosystem of packages on NPM which you can use into web applications. Uh for uh you can use material UI and uh React

3:36

Bootstrap libraries which are based on React which can which can help you to make your website development much faster And React is obviously used by Meta and it is also used by other companies like Netflix, Atlassian and many more So user interfaces are developed in React with the help of components. So React components are independent and they are developed using JSS. So JSX is a special syntax which stands for JavaScript plus XML used to develop React components and it is the most preferred way to develop React components So at the right hand side we can see a console log button React component. So we can see that this uh at the top we have imported React

4:24

and what this component does is it returns a button which has a text click main and this button has a on-click property and for and this and this property has been binded with the handle click function and then we have exported this console log button So whenever we use this button, a component, any console log button component anyone in our web app, it will render a but uh this button and once you click it a console log will happen. So Now as over here we can see that we have imported this console. log button component and we can use it in an application as many times as possible. Hence, so our React components are reusable. React components can also be developed using TypeScript.

5:10

So TypeScript is basically a superset of JavaScript uh over there in which we provide uh type definitions to variables and objects as uh by providing type definitions to the to these uh variables and objects We can locate many bugs when if which arise due to type mismatch at compile time itself. And TypeScript is getting popular, increasingly popular these days and as a per and I personally use TypeScript and it definitely helps a lot. If you want more details of React components, please head on to React documentation and the Beta React Docs. They have explained many more concepts of React components over there.

5:55

Okay, so now we like React and we came to know how useful React is for modern print end development And now we want to use React in Jack. So how can we use it? Well the first approach which comes to my mind was you can keep uh Django and you can you can treat them you can treat basically Django and React as two different uh projects like for front end and back end and the second choice is you treat them as a single project So we'll get into details of what the approach is. So in the first approach where you treat your uh front end and back end uh separate So obviously the advantage is your entire

6:41

code bases are different and over your all the interactions between your back end and front end will happen with the help of REST APIs So uh over here you have to use Django, BB you have to use Django Rest Plainwork to develop REST APIs and This approach I feel is good if you have a large team of software developers because then you will have dedicated members for who can work on front end as well as backend But over here there are some uh disadvantages as well. So in this approach you're not using all the features of Django. basically Django is a batteries included framework which and we love Django because it it provides us many features by default So

7:26

you won't be able to use Django uh forms over here. So even if let's say you want to over here in this approach you have to create a login page You have to design it with a React and you won't be able to use a Django form and then you won't be able to use Django's default authentication method. So since you will and we using Django Rest you have to maybe uh authenticate your uh APIs with the help of uh some kind of a token authentication or JWT JSON web token authentication methods And since you will have two projects, front end and back end, you have to deploy into two different locations like uh you deploy let's say you deploy your back end on Heroku

8:13

and you deploy your front end on Netly five. So your time and cost for deployment will uh increase for sure. And since they are hosted in different locations, you have to deal with cores as well So there's an another approach where in this approach you treat them as a you treat both Django and React into a in one single project And OIO, what will happen is when a client makes a request, the Django will basically return an HTML file and then client side rendering of React will take place. So in this approach you are basically using features of Django which uh you uh like

8:59

such as authentication, default authentication and Django forms. So over here you can let's say uh you have the liberty basically to decide where to use React and where to use normal HTML CSS. So consider a simple password reset page or a login page for example where you just have two fields of one is for email address or maybe username and there is a password field and there will be a simple button two for login. So over there you there's no need to use uh React because the UI is not uh that complicated or maybe uh over here bootstrap or HTML CSS is fine. So you can just use a Django firm and you're attacked. And you so you can you get that liberty

9:44

and over here in this approach Since you're it is a single project uh there will be no problem of course so basically uh all your JavaScript will be served by uh Django Le. So no problem of course and And it is deployed in one location only. So your deployment also gets easier. In fact, your deployment will be the same as we used to do before when you had just used jQuery or vanilla JavaScript. So now I will give you a demo of a of my package and how how I use this package to basically integrate React and Django as in a single project.

10:30

So to install this package uh you need to first uh run the following command Web install Django underscore Webpack underscore dev underscore server Since I already have this package and I have already added the name of this package in the installed apps list inside the settings. py file, then we can run the following command to create a React app config for our Django project. So the command is python manage. py generate react and then we have to provide an app name. Let the new app name be new front end

11:16

So we can see that meanwhile this command is being executed So we can see that a new front end folder is created and it is like a Django app only but it has some extra configuration files such as package. json, pable. config. json, webpack. config. js So Webpack is basically a JavaScript bundler and its job is to take multiple JavaScript files and combine them and create a single JavaScript file which can be loaded into a single HTML file. And then the role of Babel is basically to convert the new JavaScript code which we use for dev while developing into a JavaScript which can be understand by our which could be understood by our browsers

12:02

and uh and inside the Templates directory there is an index. html file which this package has created and we can see that there is a script tag which says that please load uh the main. js file And also in the index. html file we can see there is a dev with an id equal to app. And when we go inside the index. js file We can see that this ID, this div with that ID is being referenced over here and we can see that the app component is being rendered into this div So uh though the command is also uh executed and we can see that it uh has been uh executed successfully

12:51

and we can see that it has also listed steps What we have to do? So we just have to add this new Django in the installed apps list and the add the URLs of this app into our projects URLs. py file. So I will just delete this as it was for demonstration purpose only. So the front end Django app you see in the right hand side is also developed using the package. So now I'll show you a to-do application that I've developed using Jacko in React. So let's start the servers And now I'll start the uh front end server as well. So while developing the UI, we use Webpack Dev server.

13:36

So Webpack Dev Server is used So that uh whenever you make changes in your uh front-end code, your web page gets updated automatically without refreshing your web page. Uh so This property is called hot reloading and we start the front end server by executing npm start So this to do uh in this to do application a user can create the accounts, then they can log in and then they can create uh and delete to do items So you can see the there are login and registration pages and with the help of React Developer

14:23

Chrome extension we can see that this page is not using React. In fact these web pages are developed using uh Django forms and over here I have used uh Django Crispy Forms. So let's create a user first So now our user is created. Now let's log in So when we land to the home page of our website, so we can see with the React Developers extension that this page is using the development build of React. And this web page is developed using React Bootstrap library, which I discussed at the beginning of my talk.

15:10

So in the right hand side at the NABAR, we can see DjangoCon username displayed. So This value of the username is rendered from the request. user. username value. So we can see inside the index. html file That the this value of request. user. username is stored inside request username variable with the help of JSON script tag of Django And then this value is referenced uh inside the header component uh by uh by this Now let's uh create a to do. So let's create a simple to do.

15:55

So let's add it. So now a to do is created and if we go into the Uh Django server, we can see that this to do is created successfully and the request uh status code is 200. And since this is a POST request, uh we have to send CSRF token as well. So This is how I uh this request is created with the help of Axios. So Axios is basically a request module in JavaScript So over here I create Axios a post request. I declare my endpoint, then I pass the data which I want to send and then I pass the CSRF token and the request is sent So in this way you basically get a choice uh where to use uh React

16:42

and when to use uh same uh simple plain HTML, CSS and Foolstra So consider that you want to add a profile page over here and you have just have to add a couple of fields. So in that case you can just simply use uh a Django form. At least I would prefer to use a Django form Now let's go to localus eight thousand So now let's log in with the user which we created just right now. So once we log in, so we see nothing and with the React developers tool we can see that this page is not using React. So the reason for this is that inside the

17:27

static folder and inside the front-end folder there is no JavaScript file. To create a JavaScript file, we have to render script. So the script is npm run build and this will create a production build of our frontend code. So this will minimize code and so that it gets optimized and once this javascript file is ready So once our production build is ready, now let's go to the browser and refresh So we can say our web page is loaded as before and we can verify from the React Developers extension that this page is using the production build of React

18:13

And so in this way uh you can use React uh in some pages and you can use plain HTML CHS and BootShap in some pages. uh other pages and this will also help you to reduce the button size of your front end and which will uh improve your website's performance So, thank you for listening to my talk. I hope you enjoyed it. If you have any feedback for me, please do let me know. I would really appreciate your feedback. And if you want to get in contact with me, here are my LinkedIn profile link, email and Twitter handles. I'm super active on LinkedIn so feel free to ping me over there.

18:58

If not, you can just drop me an email or else we can connect on Twitter. So thank you and I hope you enjoy the rest of the conference

Questions this talk answers

Why use a front-end framework like React with Django?

Frameworks such as React make highly interactive interfaces faster, cleaner, and easier to build than using vanilla JavaScript or jQuery alone, especially as the UI becomes more complex.

Discussed at 2:03

Should I keep React and Django as separate projects or combine them into one project?

A separate-project setup is useful for larger teams with dedicated front-end and back-end developers, but it requires REST APIs, separate deployments, and cross-origin handling. Keeping them in one project lets you retain Django forms and authentication, deploy in one place, and choose React only for the pages that need it.

Discussed at 6:41

How do I integrate React into a Django project with Django Webpack DevServer?

Install the package with pip, add it to `INSTALLED_APPS`, and run `python manage.py generate_react <app_name>` to create a React-enabled Django app. Then add the generated app and its URLs to the project; the package supplies the Webpack, Babel, template, and entry-point configuration.

Discussed at 10:30

What is Webpack Dev Server used for in a Django and React project?

It runs the front-end during development and automatically updates the page when front-end code changes, a feature called hot reloading. The development server is started with `npm start`.

Discussed at 13:36

How can React use data from a Django request?

A Django value such as `request.user.username` can be placed in the template through Django’s JSON script tag, stored in a JavaScript variable, and then referenced by a React component.

Discussed at 15:10

How do I send a React POST request to Django securely?

Use Axios to post to the Django endpoint, passing the data and the CSRF token along with the request. The demonstrated to-do request succeeds with this approach.

Discussed at 15:55

How do I build the React front end for production in Django Webpack DevServer?

Run `npm run build` to create a minimized, optimized production JavaScript bundle in the static folder. Once that bundle is present, Django serves the page using the production build of React.

Discussed at 17:27

Presenters

Note: We understand that names change, people change, and bodies change. We respect each individual's journey and privacy. If you have any concerns about a video or need us to remove content, please don't hesitate to contact us. We will handle your request with care and promptly address any issues.

More videos from DjangoCon US