Back to the video

Integrating React in the Django way! with Jiten Sidhpura

Transcript

By Jiten Sidhpura. From DjangoCon US 2022. Published November 24, 2022.

Watch the video Markdown version 2,811 words · auto-generated · en

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.

Transcript

Automatically transcribed, so expect mistakes in names and technical terms. Filler words are removed.

0:21 Introduction

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, 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 Frontend Frameworks

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

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 they generally do this so that they can have a better user experience. and they which helps them to keep them engaged in their platforms. So and when such kind of UI if we try to develop with traditional techniques like using vanilla javascript or A jQuery library, then it might get difficult after a specific period of time.

2:50 React Fundamentals

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. For you can use material UI and React

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 at the top we have imported React

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 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.

So TypeScript is basically a superset of JavaScript over there in which we provide type definitions to variables and objects as by providing type definitions to the to these 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 Django and React Architectures

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 Django and you can you can treat them you can treat basically Django and React as two different 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 front end and back end separate So obviously the advantage is your entire

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 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 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 provides us many features by default So

you won't be able to use Django 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 authenticate your APIs with the help of 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 you deploy let's say you deploy your back end on Heroku

and you deploy your front end on Netly five. So your time and cost for deployment will 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 you like

such as authentication, default authentication and Django forms. So over here you can let's say 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 React because the UI is not that complicated or maybe 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

and over here in this approach Since you're it is a single project there will be no problem of course so basically all your JavaScript will be served by Django Le. So no problem of course 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 I use this package to basically integrate React and Django as in a single project.

10:30 Package Setup

So to install this package you need to first 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 Generated App Structure

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

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 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 though the command is also executed and we can see that it has been executed successfully

12:51 Development Workflow

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 front end server as well. So while developing the UI, we use Webpack Dev server.

So Webpack Dev Server is used So that whenever you make changes in your front-end code, your web page gets updated automatically without refreshing your web page. So This property is called hot reloading and we start the front end server by executing npm start So this to do in this to do application a user can create the accounts, then they can log in and then they can create 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 Hybrid Django and React Application

Chrome extension we can see that this page is not using React. In fact these web pages are developed using Django forms and over here I have used 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.

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 inside the header component by this Now let's create a to do. So let's create a simple to do.

So let's add it. So now a to do is created and if we go into the Django server, we can see that this to do is created successfully and the request status code is 200. And since this is a POST request, we have to send CSRF token as well. So This is how I 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 where to use React

and when to use same 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 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 Production Build

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

And so in this way you can use React in some pages and you can use plain HTML CHS and BootShap in some pages. Other pages and this will also help you to reduce the button size of your front end and which will 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.

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