Django and React: Perfect Together by Jack McCloy

This video features Jack McCloy at DjangoCon US 2016 in Philadelphia, Pennsylvania, USA.

Django and React: Perfect Together by Jack McCloy
0:43:18
Published August 10, 2016
20,994 views
365 likes

DjangoCon US 2016 - Django and React: Perfect Together by Jack McCloy

React is a JavaScript library that makes it much easier to build dynamic single-page sites. I won't much dive into how React works, but the main advantage is that it allows you to build your view layer in a declarative way, and with reusable components.

We'll start with an overview how React works, with an eye towards how it's different from interpretive libraries like jQuery. This overview will center around how state is managed in React vs. jQuery, which is the biggest hurdle for many developers when they're learning React. So if you haven't quite wrapped your head around the difference between "2-way data binding" and "1-way data binding", or if you've heard someone talk about "data-down/actions-up", "flux", or "redux" and weren't quite sure what they were talking about, this will clear all that up.

Then we'll take a look at how you can integrate React into a Django project. We'll talk about how you might want to structure things if you're starting with a brand new project, but we'll also talk about ways you can start to take advantage of React's strengths even in projects that are already mature.

Finally, we'll talk about some of the challenging parts of working with React for the first time - how to handle front-end permissioning in React based on your back-end API, how to think about url routing when you literally have two routers, deployment, and the general confusion that goes along with using npm and webpack for the first time.

This talk was presented at: https://2016.djangocon.us/schedule/presentation/46/

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

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

Summary

React can complement Django by taking over the template and UI layer while Django continues to handle models, views, and server-side business logic. Jack McCloy explains React’s component-based, declarative approach: components manage state, render JSX, and update the UI when state changes, making complex interactive applications easier to reason about than imperative jQuery code. He covers single-page applications, reusable components and React Native, one-way data flow, and when React is or is not appropriate. He also outlines a practical Django integration using Django REST Framework as an API, Node and npm for JavaScript dependencies, Babel and Webpack for building bundles, and django-webpack-loader for including those bundles in Django templates. The talk closes with guidance on Redux, routing, component lifecycles, authentication, deployment, and deciding when the complexity of React is justified.

Key takeaways

  • React is a UI layer rather than a full MVC framework, so it can replace Django templates without replacing Django’s models or views.
  • React components manage local state and render JSX declaratively, with data flowing down and user actions flowing up.
  • React is most useful when an application has complex shared state, rich interactivity, or a single-page-app interface; Django templates remain suitable for simpler sites.
  • A typical integration exposes Django data through an API, often with Django REST Framework, while Node, npm, Babel, and Webpack build the React frontend.
  • Redux can centralize application state and state transitions, making complex interfaces easier to debug and maintain.

Summarised automatically from the transcript.

Transcript

7,094 words · auto-generated Show

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

0:00

Speaker 1: Come on, yo. Hi

0:15

Speaker 2: everyone. Um so my name is Jack and I have to There we go. Cool. I'm a software developer from New York City. Um and one of the reasons why I'm giving this talk is most of my recent projects, three out of my last four recent projects were Django projects that also used uh React. So I've dug deep into how the two can fit together and I really like how they fit together. Hopefully some has anyone here worked on any React projects? Okay, so a handful. So not a room full of beginners, that's exciting. If you are a beginner, uh I kind of geared this talk for people who know Django but haven't really used React yet, are kind of just thinking about it and looking at it

1:01

Speaker 2: So um I've been a Django user for over five years, uh React user for about the last year or so, a little longer than that And for what it's worth, I don't consider myself to be any kind of expert on either of those things. Just someone who put in a lot of time working on Django projects and React projects and might have a little bit to share. I'm gonna try and talk fast. If I talk too fast, uh slow me down, but um it's kind of a broad uh scope to this talk, so I'm more worried about um not having enough time than I am about like filling time. I'll try and save some time for Q<unk>A at the end, but that's my contact info. You can hit me up on Twitter or GitHub if you have any questions that we didn't have time for today. And I'll also be around for the next couple days for the sprints.

1:49

Speaker 2: So, what are the goals of this talk? The title of the talk really could be A Crash Course in React for people who already know Django. The first goal is to understand what React does, how React works, because a lot of people are talking about it and people in the Django community, some people have kicked the tires on it, some people have used it heavily, but a lot of people haven't So it's kind of an intro to React for Django people. And the goal is to build a mental map for React so that you know how to think about it. It's going to take longer than a 45-minute talk to build a good mental map for uh React, but hopefully this will be a good primer.

2:34

Speaker 2: Um, we're going to become familiar with some of the key parts of a React project and learn how to set up a React project inside of a Django environment One of the other big challenges of learning React is that a lot of React projects and most of the React boilerplate examples use JSX and uh quote unquote new JavaScript, ES6 or ES7. Um so we'll be diving into a little bit of that just so you know what you're looking at. It's one of the things that can add some intimidation to learning React. And then finally, we'll bring it all together by showing how Django and React can fit together in a project. And we're actually going to start here a little bit at a high-level view before digging into the uh React part. We'll look at the separation of concerns in a Django and React project that uses both.

3:23

Speaker 2: So Django follows the MVC pattern for building user interfaces. In the MVC pattern, there are three parts: the model, the view, and the controller, and they're all interconnected. This is kind of how they're interconnected. The model updates the view. The view is what's seen by the user. The user can do stuff to manipulate the controller. This is based on the user's interaction with the view, and then the controller updates the model. This is how Django works, sort of. There's a cool question on the Django fact page. Django appears to be an MVC framework, but you call the controller the view and the view the template. How come you don't use the standard names? And the answer that Django gives is in our interpretation of MVC, the view describes the data that gets presented to the user.

4:15

Speaker 2: It's not necessarily how the data looks, but what data is being presented. It's sensible to separate content from presentation, and that's where Django templates come in. It's kind of a pedantic answer to uh that question but that's also part of the reason why I like it. But what they're saying essentially is that in Django the view part of the MVC is split into two Two things, the view that you keep in views. py that renders data to your templates that actually are the view that the user sees. So the map of an MVC from Django's perspective looks more like this: where the model corresponds to your models. py file, your views corresponds to your views. py, they render data to your templates.

5:00

Speaker 2: Which is what the user sees. He or she interacts with the templates to manipulate the controller, which is kind of like the framework itself, and the controller updates the model. React fits here. React fits where the templates are. It replaces your Django templates and based on how the user interacts with those templates, dispatches actions that then update Django, that update the controller. So, this is what your MVC looks like in a React project. The first thing about React to understand is that it's not a full MVC framework and it doesn't try to be If you use it in a Django project, it'll fit where your templates used to fit. It won't replace anything else in a Django project.

5:49

Speaker 2: And keep in mind templates, like it's the broad view of templates. It's not just the templates files, but also the files and packages that your templates use jQuery, potentially CSS, all of your JavaScript files that are imported into your templates. So, why would you want to do this? Django templates work perfectly well. Why would you want to start uh stop using them? and start using something that is significantly more complicated. No, sorry about that. That you have to learn from scratch And that's outside the Django ecosystem that you already know real well and love. And the answer to that is maybe you don't.

6:35

Speaker 2: Maybe you don't want to use React and it would be over-engineering to use React. Django templates are perfectly fine for plenty of sites, and we all know that because we've used them for plenty of sites. They work. But React lets you do certain things that would be really, really hard to do, if not impossible to do, using just Django templates. The first thing that React Templates let you do is it lets you turn your site into a single-page app. From the user's perspective, single page apps, when they're built the right way, they are faster, they feel more modern. Something that's really been popular in the JavaScript community for a couple of years now and has been a little bit slower to become popular in the Django community

7:22

Speaker 2: and the uh Ruby community. I know that channels are doing some work To be able to use templates to build single-page apps, but this is a big reason why React is deserving of a look. Another thing that you get with React is the ability to reuse parts of your code base for iOS and Android in addition to just your web app. I'm not going to dive too much into this, but it basically works like this. Your React templates are made up of components. They're like building blocks. That you assemble together to form your UI. And each one of those building blocks does two things. It performs some internal logic. And then based on that internal logic, it renders a chunk of what your users see.

8:10

Speaker 2: It renders a chunk of UI. With React Native, you get to keep the part of your templates that perform that logic. and use them across platforms and then render out different code, either HTML or iOS or Java, based on the platform that the user is using. And then finally, and this is probably the biggest reason why React is caught on as big as it has, is it makes it much easier to manage and manipulate complicated state. In most small projects, there isn't complicated state. The state is simple, so there's not much to manage. You can keep it all in your head more or less. When you start working on a bigger project, Managing state can become a real nightmare. And I'm sure it's something that you've potentially run into.

8:58

Speaker 2: That is the biggest selling point of React and the biggest thing that it makes much, much easier. So, we're going to zoom in for a bit on the React part of this map so that you can understand understand uh and get a feel for that. And then we're going to zoom back out and look at how Django and React work together as part of a full system. Oh, and one more thing. Since React is taking care of your UI, your views are going to feed it raw data. Your view layer is really just an API layer. React doesn't care what the rest of your stack is, but using something like Django REST Framework is uh it makes a heck of a lot of sense because then your views are just an API layer by default. So, the homepage for React highlights a couple of things that differentiate it from other UI frameworks.

9:49

Speaker 2: Um if you understand these three things you'll understand the fundamentals of React. The first one we already talked about it's that React doesn't make assumptions About the rest of your technology stack. React is your UI layer. It provides a really good tool set, arguably the best tool set for building your UI, and it doesn't try to do anything else other than that. The second point on the homepage is that React is declarative. And this one is a little bit tougher to grok. React makes it painless to create interactive UIs. You might put an asterisk after the word painless. It's painless once you go through the significant pain of like learning how to use it.

10:34

Speaker 2: But once you understand that it is pretty painless, it's actually very painless. And yeah, it's quite easy to use once you get it. You design simple views for each state in your application, and React will efficiently update and render the right components. When your data changes. So basically, this means that when you use React, your application state is kept separate from your DOM. You declare what your DOM should look like. Given a certain um state that your application is in. Then when your application state changes, your DOM changes as a result of that, but React controls this change. You don't control this change, you only manage the state and what the state

11:22

Speaker 2: and what the DOM is supposed to look like given a state. And then finally, declarative views make your code more predictable and easier to debug. It also makes your code a heck of a lot easier to test. So, how a declarative component compares with doing things the interpretive way with uh jQuery. Let's say you've got a very simple uh page. You got a button and a div, and you have two views. Where state one is the button shows the word hide and the div is there. State two, the button shows the word show and the div is not there. This is how you'd code it out in jQuery. I'm not including the actual HTML page where the DOM elements are declared, but you'd have a JavaScript file. You'd bind the click event to your button.

12:09

Speaker 2: That click event will call a function every time it's fired. That function's gonna check what state the div is in, uh whether the div is visible or not, and then interpret from that state whether or not The um div should still be showing. It'll interpret your application state based on what it sees. And from that interpretation, it's either going to show the div or hide the div The state is interpreted from your DOM. I know this is really bad jQuery, by the way. Um but yeah, how you would do the same thing in React. It's going to look very differently. React uses components. We already talked about that a bit. And this file represents a single React component. The uh easiest way to think about components is as a container for some part of your UI.

12:58

Speaker 2: And uh this code looks uh it uses ES6, so it might look a little bit different than the JavaScript that you use We'll talk about that for just one second. ES6 is the 2015 JavaScript specification. It adds a whole bunch of stuff. To JavaScript that never was there before. It adds classes, it adds modules, so you can import and export JavaScript from files just like you can with uh Python packages It adds iterators and generators, promises. There's also an ES7, which was finalized last month, but isn't really widely supported yet. The point is though, JavaScript's evolving, and as it does, it's becoming way more Pythonic. Uh, these are a handful of tweets that I found just of people noticing the similarities between modern JavaScript and Python, my favorite.

13:49

Speaker 2: Um is it turns out ES it's up in the corner on the right. Turns out ES6 is basically Python with the added bonus of irritating front-end devs Uh and this is me joking a year ago that by the time they get to ES9, JavaScript and Python are going to be syntactically identical. So back to the React component that we're looking at. It represents a single section of your UI and it does two things inside. Uh the first thing that it does is it manages the state of this UI section, and the second thing it does is it renders the component itself. It actually renders the DOM elements based on this state. The internal functions, I collapse them so that we can see the component as a whole. At the top, uh

14:34

Speaker 2: we have the um we import React and Component. uh because this file is going to be a react component. We create our component as a class that extends the base React component. We can do that now. Inside our class, inside our React component, we have three function functions: the constructor, a function called toggle showing, and the render function. And then we'll look at all three of those in a moment. But all the way at the bottom we have our export statement to export the component. So this is one thing that Python and JavaScript are a little bit different on. In Python, every named object is exported automatically In JavaScript, you have to explicitly export the things that you want to export to be able to import them somewhere else.

15:21

Speaker 2: So let's go back and look at those three internal front functions. The constructor looks like this. It sets the properties and the initial state of your component. We haven't talked about properties and we probably won't get a chance to talk about them, but they're essentially immutable parameters that you that come from other components. You cannot change them in the context of the component that you're looking at. In this case there are no properties, but there is some state. There's a state made up of a single Boolean saying whether or not the div is showing. Toggle showing is a function that when called toggles the is showing value, the state, from true to false or from false to true. Uh we use this. setState to do that. It's how you manage internal state inside a React component.

16:06

Speaker 2: And then finally, the render function is exactly what you'd expect it to be. It's w it what it's what gets rendered. In this case one of two things can be rendered and it all depends on the value of this. state dot is showing. What's rendered is JSX. It's very similar to HTML but you can use variables inside JSX the same way that you can use variables inside um uh Django templates. And uh yeah I just want to talk for a second about the on-click property That we put on each one of those buttons. It calls that toggle showing function that we defined that switches the internal state. And since the component states change, the component is then re-rendered based on the new state.

16:52

Speaker 2: If you've ever heard the expression data down actions up. Or one-way data binding or one-directional data binding, this is what people are talking about. When you hit the click button, that action, the on-click event, travels up the component. It changes the component state, and then that new state causes the render function to be recalled based on that new state, and that data flows down. The actions go up and the data goes down. Back to the why. Might not seem like this pattern is any easier, and it's definitely a more complicated pattern for simple sites. In this example, there's very little state. Where React shines is in examples where there is a lot of state to manage, and when different components are affected by the same state.

17:43

Speaker 2: So that brings us to the components themselves. React, if you haven't picked up on this already, is component-based. You build encapsulated components that each manage their own state, and then you compose them to make complicated UIs. Since the component logic is written in JavaScript instead of templates, you can easily pass rich data through your app and keep state totally unrelated to your DOM. Uh so we just built a single component. The way to build a complex React UI is to assemble these single components together like Legos. Your React app shouldn't be a monolith, it should be a collection of components that each ideally does a single thing or renders a single part of your UI. So let's look at an example where you have a single-page app that has two views.

18:30

Speaker 2: use, a landing page and a pricing page. We want to build this as a single page app. So the top of our component, uh so the top component in our tree is going to be the same in both cases. I think I called it index. Um having the same parent all the way at the top, that's what makes it a single-page app. Uh there's a plugin called React Router that I'm not gonna have time to cover. It handles URL routing inside a React app. But I just wanted to let you know it exists. And then the index component is going to render one of two possible components. based on the properties it gets from React Router. It's going to either render landing or pricing. Landing's a component that renders your landing page, pricing is a component that renders your pricing page.

19:18

Speaker 2: Each of those pages might be made up by other components, might be made up by a whole tree of other components. But the render page of your index method is going to look something like this. Where our top component, index , is not rendering HTML, it's rendering other components based on the properties that it gets from the router. So render can render one of two things. It can actually render DOM or it can render other components that eventually further down the tree render DOM. And when the path name from your router changes, what's rendered changes without a page reload. So your application is built like a giant tree where the current view is made up of all of the components being rendered all the way down to the base of the tree.

20:11

Speaker 2: And when your application state changes, all the components below it that are being rendered are going to internally check whether they need to change too. And if they do, they'll re-render. It sounds like that would be super inefficient. Uh the way that it works is actually very efficient. I'm not going to get into that, but um it's really fast and performant. Uh there's way more to say about React, but I want to bring it back and show you how to integrate React within Django project because that's what this talk is about. Um so lightning round. This is how you uh get started using Django and React together. Uh the first thing is that you need um node uh for it. Uh node is what's going to manage all of your JavaScript packages, uh

20:58

Speaker 2: including React. So you want to install Node and NPM, which is the node package manager, and then you want to initialize npm inside your Django project. And this is going to create a file called package. json. And package. json is similar in terms of what it does to requirements. txt for pip. You uh want to install the node packages that you need, and the way to do this is um npm install package name. and then have a little flag at the end to define whether you want that package installed globally, whether you want that package installed for dev dependencies, for development only, or for development and production.

21:46

Speaker 2: So here is what uh selection from my package. json from one of my projects. Um just a couple of things. These are all the dependencies for this project. uh that's needed for prod and also for dev. A couple of things to focus in on. All of the stuff that starts with Babbel. Babbel is a shim for lack of a better word, that takes your ES 2016 or 2015, your your ES6 JavaScript, and reduces it down to JavaScript that older browsers can read. Uh radium is a package that you probably won't use in a typical React project. I like it a lot because I have a vendetta against CSS, and one of the things that

22:32

Speaker 2: React lets you do is eliminate all CSS. Radium helps helps you do it by letting you do media queries within React without using CSS. Webpack stuff, all the stuff that starts with Webpack. Webpack is a module builder. It builds the bundle for your app that your Django template is going to read from and build the app from. Um both for prod and for dev, it's probably for you gonna eliminate the need for tools like Grunt and Gulp. And it also gives you hot reloading. So just like when you change When you change a Python file, your server uh restarts. When you change a JavaScript file, your node server will be able to restart if you use WebPath. That's not the only way to do it. It's just kind of the preferred way to do it, I guess,

23:20

Speaker 2: or a preferred way to do it. And then finally, something that I am probably not going to get a chance to talk about. Is Redux , which is something you should learn and make use of. It's a package, it's also a pattern for managing and updating application state that lets all of the state updates happen in the same place. So you can simplify state management even further and also put dev tools there so it's easier to see what's going on. So, yeah, the next step is learn Redux. It's 100% worth the time it takes to learn. There's a really good video course. by the creator of Redux that I link to here. I'll publish these slides afterwards, by the way, but you should definitely check that out if you uh if you care to learn React.

24:10

Speaker 2: Then the next step is you make a server. js file. This is the file that you use to um run your node server in your dev environment. It's kind of like manage. py run server. You would do node. server. or node space server. js to start your node server. Mine looks like this. And it basically just tells your web back your webpack development server how to run. And it makes you use of a configuration file where you store all your webpack configurations. Making that configuration file is the next step. Um the config file, I couldn't fit the whole thing uh

24:57

Speaker 2: on here. Let me see if I can actually can you see that or no? Hang on. You see it now? No. Alright. There's a gist to it. So I'm gonna have to describe this without showing it, unfortunately. And now I've made it so that I can't see it. Yeah, but in your webpack uh config it gives you You the ability to use different uh loaders, to use different modules, to use um different uh inputs and outputs. The inputs, they're called entries, and the outputs, which is just called output,

25:42

Speaker 2: is the part that you're going to be most concerned about. What the output does is it tells Webpack where to put that big old bundle that it creates So that JavaScript knows where to look, so that Django knows where to look for it. And then entry defines what the top component in your React component tree is. So if you want to slowly integrate React into an existing Django project, you might have multiple entries. small React app inside Django to manage a small thing that can grow over time. But you could have multiple entry points, multiple React trees, I guess you would call them, and you would define them in your Webpack config. Um I only have one and I call it main.

26:33

Speaker 2: There we go. I can see my notes again. But yeah, there's a gist to that in there. There's also your index. jsx file, which is your topmost React file, which I included a gist to. And then two more components that index. jsx uses. Approot, which is where your app 's roots are defined. and app. jsx, which is the uppermost component that render that has the potential to render DOM and not just render other components. It'll render other components too, but it can also render DOM, like a loading DOM. And then finally here's how you hook the two of them uh together. You install uh Django

27:20

Speaker 2: Webpack Loader, which is a nice little package that lets you call your Webpack bundle. So all of that um React code and the other JavaScript packages that you're using lets you call that from inside a Django template and you add Webpack Loader to your installed apps. And if you have multiple entry points, you'll want to do some additional configuration that's really well documented on Webpack Loaders. GitHub. And then finally, the last step is inside a Django template, you load render bundle from your uh from Webpack Loader at the top of the page And then inside the HTML of the page, we render the bundle that we're trying to render.

28:07

Speaker 2: We called it main in Webpack Config. So it just says render bundle main. And that's it. That is basically how to integrate um it into a project. So I have more stuff that I can cover and I'm prepared to cover, but I figure now would be a decent time to stop for like two or three minutes of questions. in case anyone wants to jump in, because I know that it might be uh green territory. There are uh microphones.

28:39

Speaker 3: Um we use the same code base. Sounds amazing. But I would like to know what is the reality of that because I'm glad to say exactly the same, but I don't think you haven't your component your logic right and then your render

28:57

Speaker 2: sure

28:57

Speaker 3: you're actually rendering different things right and you in a web application you have different components as well. So that what is the reality of that?

29:06

Speaker 2: Yeah, I mean I haven't worked too much with it, but I know several people that have the kind of you're you're talking about with uh React Native, right? Yeah, so um React the first of all iOS React Native is more mature than Android React Native right now, so most of the problems that people are having. seem to be coming from Android uh React Native. It's good for certain types of applications, applications that like render template views. It's bad for Applications that are super animation heavy and have a lot of like interstitial animations um is also what I've heard in terms of structure that project. React lets you do it one of two different ways. Inside a component, you can render different code based on

29:54

Speaker 2: the um based on whether it is a web app or an iOS app or an Android app, another thing that you can do is you can have different components To define what your app is. So you can have index component. jsx next to index component. ios. jsx and you will just import that as index component and React is smart enough to know that if you're building an iOS app, it wants to use the one that's iOS and if you're building if it's a web app it wants to use the one that's uh JSX. Does that answer it at all? Yes. Okay. Yeah, I mean I think that the benefit is if you want your mobile app to do totally different things than your web app, you probably wouldn't.

30:43

Speaker 2: But if you want your mobile app, if it's really just a distribution game, where you want your Android app and your iOS app to be very similar to one another, then being able to share the same code base, I think, makes a heck of a lot of sense.

30:55

Speaker 4: So I have two quick questions. You mentioned Django Rest framework and React.

30:59

Speaker 2: Yeah.

30:59

Speaker 4: Um what's the workflow look like for login, for example? And And sending back a CSRF token and am I simply just grabbing that token on the JavaScript JavaScript side from the cookie and appending it to every request? Or what's the React way of doing that?

31:14

Speaker 2: Yeah, um I'll show you some code afterwards or if you're around for the next couple days. Basically the way that I do it is I have Ajax calls inside my Redux workflow where I make a From the perspective of a component, it I just have a call that says get uh artists or something like that. And inside that get artists function that I'll define, it's going to check what artists I already have in my uh Redux store. Redux is kind of like the back end of your front end. I know I'm getting deeper than I wanted to on this, but it'll check if I need to make a fetch. First of all, it'll check if I need to make an Ajax call. If I do, it'll make that AJAX call, get the response, and then load it into my browser's local store.

32:04

Speaker 4: Okay, cool.

32:05

Speaker 2: Um yeah, I I appreciate that that probably doesn't fully answer your question.

32:10

Speaker 4: No, that makes sense. Um and my next question is um React can get really complicated, as we know. You can have models and a lot of business logic on the front end. You can do the same thing on the back end. In your experience, how do you handle where that logic should land as far as uh Django models or models in React But where do we draw that line?

32:30

Speaker 2: Sure, uh React doesn't have models, it has modules. So you're like importing modules from it's not like Django models so much. I guess your React data stores could be similar to modules, but those would be populated by your Django models. So what I would typically do is I would get the data from Django, put it into React so I don't have to get it again if I need it again. and sort of use it the same way that you would kind of use like SQL Lite if you were building an iOS app where you have like a local data store just for that user, just for that session. and then everything else just lives in Django.

33:16

Speaker 2: And you have a workflow where you check if you need it. If you do, you grab it from Django. If you already have it, then you don't.

33:24

Speaker 4: Alright,

33:24

Speaker 2: thanks. Yeah, of course. Oh

33:27

Speaker 5: , hi. I've really been appreciating a lot of the conversation I've heard around Django and React together. Um my question for you is about uh style management and CSS. like CSS , and that you're using Radium for media queries.

33:41

Speaker 2: Sure.

33:41

Speaker 5: Are you using any other libraries? Uh Khan Academy has one, I forget the name of it, to manage uh inline styles in virtual DOM elements?

33:49

Speaker 2: No. Uh I'm not using those. Basically my CSS is so I've um put a kind of rigid separation between components that render pages. are only made up of other dumb components that don't manage any internal state. So I have a component for button and I have a component for div. and things like that and I define what those should look like by passing props to them and then all of the radium calls are done internally. And I really actually only use radium for the hover and focus media queries, things like that. For things like width, I do that declaratively by having a reducer that manages the window width so I can access that in a declarative fashion. Does that answer your question?

34:34

Speaker 5: Yeah, it it does a bit. Um how do you reuse any style share between between components?

34:40

Speaker 2: Sure. Um you just have it inherit from uh parent. Like I i if if you're using the same button everywhere, you you really don't have to. You're importing the button into your component. So it's not like your your button almost becomes a composite of the DOM element and also the style in the same way that it would be if you had a button that you put like I don't know a button success on if you're using Bootstrap

35:06

Speaker 5: Right. Thank you.

35:07

Speaker 2: Yeah. Uh

35:09

Speaker 6: my question is about a little bit of architecturing or maybe deciding when you are um Where where you should migrate your application to something like React. Like for example, the uh the button example that you made is trivial in in jQuery, right? Yep. But um How do you know when hey I could really use something that manages my state instead of just adding classes to my stuff and checking uh with jQuery? But you know installing uh React is not uh Like oh a one command thing. Right. You really have to commit to it. It's probably gonna change your build and a bunch of stuff.

35:48

Speaker 2: Yeah.

35:49

Speaker 6: So when do you know hey we should really be using something more robust than just jQuery, you know?

35:55

Speaker 2: I mean I I would say if you're starting a new project then you already know reactive makes a lot of sense because it's no harder to do it that way if you're starting from scratch. If you have an existing project that isn't using React. I mean, you'll know when you're spending a lot of time debugging uh jQuery because managing state is an issue. So like how you do that exact calculus of whether or not the investment is worth it really has a lot to do with how much of a headache it is to uh fix problems um that that happen when your state and your DOM are like intermixed. So

36:36

Speaker 7: Heath, uh thanks for the talk. I have heard a lot of different opinions about combining like front end and back end and especially in our Django projects. And I'm wondering how you handle uh packaging up your uh your project for deployment uh since A lot of people have opinions about separating front end and back end bundles and whatnot. Like a lot of people that I work with are really against having PIP, you know, be dependent on NPM. And I tend to agree with them but I wanted to see what you thought about that.

37:09

Speaker 2: Um yeah, I mean I tend to agree with that as well. Like uh uh Python Django has to run on the server, it's backend. Um React can either be deployed on the server or on the uh client it's um front end I like to keep them separate. Um yeah.

37:28

Speaker 7: Thanks.

37:28

Speaker 2: Does that does that answer your question? No, it's one of the keywords, yeah

37:33

Speaker 8: Thanks for the talk. This really demystifies React and makes it clear this is a state-based view technology. Yep. So um Uh the previous call uh previous questioner somewhat got into the issue that I wanted to know about, which is when you're in development, you mentioned and running node um both as a sort of compass-like watcher and also as a server for development to serve up some resources that Django is gonna call for. In uh production and deployment, I gather that you don't do that, and I just wanted to verify that that's true.

38:10

Speaker 2: That's exactly right. Yeah.

38:11

Speaker 8: Okay. Thank you.

38:13

Speaker 2: So cool, we have five minutes left. Uh if there's any more questions, if not I'll jump into some stuff that I wanted to cover but didn't have uh time to. Awesome. So stuff I wish I had time to cover. This is also a really good, like um, I don't I don't know, study guide for what to do next if you're gonna start doing um Any React development. The first thing is the component lifecycle. So inside every React component, there are seven things that can potentially change the props or the state. of that React component. It's only seven, but knowing what they are, knowing when they're called in terms of when a component gets instantiated when a component gets released,

39:00

Speaker 2: they call it mounted and unmounted, can be really helpful. I have a slide in this deck that you can look at that like does a breach Description of what each one of them is. The next thing is flux and redux. So flux was the uh Little history, React came out. Some people found that managing state in-between components in React was sometimes challenging. Someone solved it with a pattern called flux that let um state be stored in one place relative to a component, and then other components lower down the tree would access that state indirectly. They would access that state as properties, so they couldn't edit it directly. but then they could pass actions back to a flux store that would then cause it all to update.

39:50

Speaker 2: The problem with that is you would have a whole bunch of different flux stores at different levels of your app. Redux, which is kind of a flux-like architecture that everyone's moving towards. It is like flux, except it says all of your state transformations, all of your state transitions. should happen in exactly the same place in a Redux store, a reducer. And what that lets you do is you have your application state all in exactly one place as a giant JSON tree. basically, and your application renders from that. And if you want to change anything in your application, if you have a button click or whatever, you don't do it internally in the component. You dispatch an action

40:37

Speaker 2: to your Redux store and what Redux does is it preserves your last state but also creates a new state for your app to Transition into. What it lets you do is debug things a lot more easily because you have what your state was and what your state now is. So anytime you can hook up so that anytime an error gets thrown for a user, that it sends their entire state history to a server so that you can debug more easily. It lets you see what your React state what your application state is all at one time, all in one place. It's super useful to learn. React router and Redux router, those are the two routers that people use for URL routing inside of a React app.

41:25

Speaker 2: They do essentially the same thing. React router is simple and perfect. Perfect for most apps. Redux router adds some more functionality that React router doesn't have. It's probably too comp uh it's not too complicated. It's probably over engineering for most apps, but if you need it, it's great. Uh yeah, I will put some gists for authentication and access restriction using Django, because that's something that I kind of scratched my head on for a while. I'll add that to the slide before I publish it. Basically you wrap your components inside an authentication wrapper that checks whether or not a user is logged in prior to rendering the component. And then yeah. Cool, I'll guess a line with this.

42:10

Speaker 2: Uh learning React isn't hard because it's hard. It's hard because it includes a heck of a lot of patterns that you're probably not already familiar with if you haven't used it before. There are a bunch of little things to learn that are each easy on their own, but altogether it makes learning React feel overwhelming at the beginning, or at least it did for me. But once you know React, it can make state management inside a complicated app much, much easier. It plays really nice with Django because it doesn't try to do the stuff that Django already does well. It tries to do one thing, manage your templates, and it does a really, really good job at that. So uh like I said, feel free to reach out to me. I'm on Twitter, I'm on GitHub, and I'll be here for the next couple days for the um

42:56

Speaker 2: for the sprints. Thank you all so much for your time.

Questions this talk answers

How does React fit into a Django project?

React occupies the template/UI layer: it replaces Django templates but does not replace Django’s models or views. Django can provide the data through an API, often using Django REST Framework.

Discussed at 5:00

Why use React instead of Django templates?

React can make it easier to build single-page apps, reuse UI logic across web and mobile with React Native, and manage complicated application state. Django templates remain a good choice for many simpler sites.

Discussed at 6:35

How does React manage state and update the UI?

You declare what the UI should look like for a given state, and React re-renders the relevant components when that state changes. Components manage their own state, with actions flowing upward and data flowing downward.

Discussed at 10:34

How do you set up React inside a Django project?

Install Node and npm, initialize npm in the Django project, and use Webpack to build the React bundle. Django Webpack Loader then lets a Django template load the bundle, such as with a `render_bundle` call.

Discussed at 20:58

How should business logic and data be split between Django and React?

The speaker generally keeps the core data and business logic in Django. React can cache data from Django in a client-side store for the current user or session, fetching it only when it is not already available.

Discussed at 32:30

When should I use React instead of jQuery in an existing project?

For a new project, React can be adopted from the beginning if its approach fits. In an existing project, it becomes worthwhile when debugging jQuery and keeping application state synchronized with the DOM have become a significant headache.

Discussed at 35:55

Do I need to run Node in production for a Django and React app?

No. Node and the Webpack development server are used during development; the speaker confirms that you do not run them that way in production.

Discussed at 38:10

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