Frontend Development for Backend Developers

This video features Robert Townley at DjangoCon Europe 2019 in Copenhagen, Denmark.

Frontend Development for Backend Developers
0:52:41
Published April 23, 2019
5,285 views

Summary

Robert Townley explains how backend developers can adopt frontend tools incrementally while keeping Django as the application’s stable foundation. Using a deliberately simple Django app serving Will Rogers quotes, he demonstrates npm for dependency management, Sass for maintainable CSS, BrowserSync for faster iterative development, Webpack for bundling and modular JavaScript, and React for replacing one interactive button. He stresses that each addition is technically overkill for the example and that developers should adopt tools only when their benefits outweigh the added complexity; he gives similar advice for state-management libraries such as Redux, which become more useful when many parts of an interface must share and respond to application state.

Key takeaways

  • npm provides a frontend equivalent to pip for recording and installing JavaScript dependencies, though treating node_modules as Django static files is only a temporary stepping stone.
  • Sass improves CSS through nested selectors and variables, while BrowserSync can make frontend iteration faster by reloading changes without manually refreshing the page.
  • Webpack bundles assets and enables JavaScript imports, helping avoid global variables and script-tag ordering problems while also reducing or organizing frontend downloads.
  • React is best introduced where interactions involve significant changing state, not for simple behavior that Django templates and ordinary JavaScript already handle well.
  • Global state libraries such as Redux are most justified when many components must react to the same user actions or when the interface can enter complex states.
  • Frontend modernization does not need to be all-or-nothing: tools can be introduced one at a time in response to specific problems.

Summarised automatically from the transcript.

Transcript

8,414 words · auto-generated Show

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

0:04

Speaker 1: Okay, hey everybody. Uh yeah, I think uh a lot of people don't feel super good about the front end part. Uh And uh that's what I'm here to today to talk about. Uh cool. Let me see if I can get this. Oh, there we go. Okay. And which is it? Bring up the speakers in. Cool. Okay. Uh hi everybody. How are you? How are you all doing today? Like collectively, you know. Sufficient levels of caffeination in the room, uh people, you know, feeling reasonably spongy in their brains right now.

0:53

Speaker 1: Okay. Um so my name is Robert Tunley. I am a senior web developer for Atlantic Media in Washington, D. C. And for the next half hour, I will be talking to you about front-end development for back-end developers. This talk is of course a follow-up to my other wildly successful presentations, including swimming for birds, uh bicycling for fish, and of course uh creative writing for professional wrestlers. I am uh I'm very grateful to uh DjangoCon for you for giving me the chance to give this presentation and I am even more grateful to all of you for coming out to hear me speak. Uh it is a huge vote of confidence that over the next uh half hour to an hour I'll be able to fill your brains with something useful, and I promise I will do my best to live up to that promise.

1:43

Speaker 1: This presentation is sorry. This presentation is geared towards a reasonably narrow band of uh band of people. If you're not yet super familiar with HTML, CSS, and JavaScript. Uh this is there's gonna be parts that are gonna be confusing for you. Um if you're a core contributor to React or View, you are going to be extremely bored and I will not blame it you if you want to go grab a cup of coffee or Go across the street next door to go grab a quick skateboard break. Uh that is totally reasonable too. Uh personally, I put myself somewhere in the middle. I've had some successes uh building out different web applications. I built reasonably complicated web applications with Vue. Recently just deployed my first React Native mobile application and at work I've helped

2:29

Speaker 1: incorporate a couple of reasonably to moderately advanced build processes for some of our Django applications. But it's been hard. It's been a very sticky process. Um it reminded me of uh back before I became a Django developer, I was doing most of my work with PHP. And learning Django Just felt like having something fall into place. Uh model template view architecture just made fundamental sense. Uh the ORM was so much better than writing raw SQL. You could get something close to peace of mind when it came to database migrations using Django. Uh the better way of doing doing things just clipped. It wasn't that way when uh years later I was trying to move beyond jQuery into the world of modern front-end development.

3:14

Speaker 1: I was bashing my head against React, Node, and Webpack tutorials month after month. Really smart people were telling me, you know, smart people who I trusted were telling me. that these tools weren't all just hype, that at the end of it the end of this process I was gonna come out of it being able to build some truly cool fun stuff But I just couldn't see it. I didn't get what's what's wrong with jQuery? Uh why do I need these ten different random libraries to perfectly have the moon align to play nicely with each other. Uh do I need to give up Django if I'm gonna just become a node developer? If you know what JavaScript is now on the back end too. All these are uh really uh confusing thoughts and I think they stommied my process because I was trying to uh eat an elephant doll in one bite

4:02

Speaker 1: The goal of my talk is not to make you front-end experts, but to answer these questions that developers trying to modernize their front-end skills might encounter. And to give you ways of doing it within the familiar, stable, and powerful context of a Django application. So today we are going to talk about some ways to uh integrate some of these tools into a Django project. And as we do so, I'm going to introduce you to a man named Will Rogers. Oh, sorry, that was that's gonna that slide. Cool. I got married a few a few months ago to a woman from Tulsa, Oklahoma. For those of you who have never heard of Tulsa or Oklahoma, if you were looking a map of the United States, it is directly square in the middle of it.

4:49

Speaker 1: Uh the airport in Tulsa, Oklahoma is named after one of Oklahoma's most famous citizens, Will Rogers. Not to be confused with uh Fred Rogers, the man who was uh behind Mr. Rogers' neighborhood, Will Rogers was a cowboy philosopher. Uh he did perform he got on horses and spun lassos and performed and did tricks while just stream of conscience uh talking about what was on his mind and eventually people uh started just listening to the things that he had to say and he didn't really have to get up on the horse anymore He was a kind man. He was funny. He cared about people. He cared about ideas, mental models, and the quality of thought.

5:36

Speaker 1: He did he cared about learning and he didn't care where that learning came from. So Okay. Much that that instantly sounds much better. Thank you. Thank you. Uh anyway. I thought of him uh when it came time to give this talk because uh the idea of a thinking cowboy. Uh I think he would like this place where a bunch of curious people gather in a strange building to discuss things that excite them. This is the uh application that we'll be working with. I have uh on my local run

6:21

Speaker 1: server over here. Yeah, he's great. Uh I have this a uh application running on my local run server, uh which we will the the application serves up Will Rogers quotes and we will be over the course of the next little while incrementally improving it with some modern tools and uh front-end techniques. Okay, so let's get started on uh looking at the actual Django project. Uh the app itself is pretty simple. It has one app called Quotes, uh which contains a model representing each quote. A view that serves up the model and an admin page that lets users add, remove, or edit quotes.

7:09

Speaker 1: The view, going back to the view, the view itself uh retrieves a random object in the database and passes it into the template context before rendering. The template itself makes reference to three static assets. We have a uh custom CSS style sheet to make the app look a little bit better. We have a CDN supplied jQuery, and we have a JavaScript uh uh file that contains all of our user interactions. Uh the interactions within that JavaScript file are relatively simple. The app ensures that a user is paying enough attention to one quote before move allowing it them to move on to the next one. If you have not waited ten seconds then you receive an obnoxious alert as uh telling you to please wait more for the next uh the next update.

7:55

Speaker 1: Uh if the user has waited, then uh window. location. reload is called and the user gets a new randomly generated quote. Pretty simple and uh it's going to be fun to remake it. This is my favorite quote. Good judgment comes from experience, and experience comes from bad judgment. Sorry. First uh the first thing that I want to mention about this app is that this app is perfect. Uh It there's there's nothing wrong with this app. Every s we are gonna be going through five steps to make it incorporate five different tools. Each one of those is absolutely over-engineering and total overkill.

8:40

Speaker 1: And I'm not just saying that because this is a dummy proxy app that I made for the conference. You're going to encounter apps throughout your daily life where someone is going to come across and say, like, yeah, we really need to add Vue into this, or geez, that that really should be handled by a build process. And the answer is not necessarily yes. The answer is going to be oftentimes, it works totally fine, that is added complexity and mental overhead, and we should not have to think about it. Part of learning these tools is figuring out where they directly apply. So my hope is that by giving you guys a taste into some of these tools, that you will uh better learn where to apply them. Also, maybe have some ammunition in your pocket when an overzealous person on your team decides they really must have the the latest, shiniest toy.

9:27

Speaker 1: Okay, uh the first thing we're gonna do is add uh a front-end package manager to the app. We are gonna add npm. npm stands for the node package manager. Node is the front-end uh runtime, sorry, the back-end runtime environment that makes back-end JavaScript possible. NPM is the package manager for Node. Uh it's pretty directly comparable to pip in the Python world and in that it's used to download and install and keep track of external dependencies. For that reason, I think this is an easier sell for a lot of Django developers. Uh if your only front end is d uh uh dependency is jQuery, similar with uh packages and apps that you're developing in the future. Uh even if you aren't using Tween for animation, moment. js for time and Axios for making asynchronous requests, uh

10:15

Speaker 1: having a requ having a package. json file in your project uh does a lot to give new new uh contributors to your project an understanding of what it is that you'll be doing. Okay, so how do you use it? Uh to get started with it, you have to first have an up-to-date uh version of Node installed on your computer or server, and then you initialize it uh from the project directory with npm init. From then on, any commands you run to install the library, uh install libraries are contained within package. json and package lock. json files. You don't have to run the equivalent of pip freeze because dependencies are automatically saved to package. json as soon as you save the file, as soon as you run the command. Okay, so uh let's add a couple of dependencies into our project first.

11:01

Speaker 1: Uh first we know we're gonna be using jQuery, so we install that by running npm install jQuery. Once that finishes downloading, you can see that our a package. json ha uh file has been modified. I don't include that, sorry. Uh uh has been modified and that we have now generated a new folder called node modules which contains the actual files that you've downloaded through the package manager. Uh adding in another library called normalize. css, we will be incorporating both those into the project. Um let's see. Looking inside of node modules, uh, you can see that that that is where the actual jQuery installs have uh taken place. This is kind of a quick and dirty way of getting node modules into

11:47

Speaker 1: uh a Django application, and uh a lot of my teammates who are better front-end developers than I have uh are totally agased by this. The idea here is that you're taking the entirety of the node modules directory and treating it as a static applic as a static folder. In doing so, your collect static is going to be gigantic. You are going to suddenly be moving thousands of files into your collect static directory. And this is a step that once you have uh become a little bit more comfortable with Webpack is not the right way to do it. But in the meantime, if you are just hoping to get some uh dip your toes into front into uh keeping keeping track of your packages within pac within npm, this is uh as good of a stepping stone as I had found.

12:34

Speaker 1: So within settings. py we declare node modules as a static directory. Um Having done this now, we can within our templates reference files that are contained within the node modules folder. You can see here that we are now referencing normalize. css within the template. And we have replaced the script tag that was referencing the CDN hosted jQuery with now our self-hosted jQuery that is served up from the node modules directory. Okay, and with that, uh newbies who are coming into the project will be able to understand uh the different JavaScript dependencies that you're using. You're keeping track of them for yourself, and uh you have more independence for later on pursuing different parts of the project. Uh we have successfully incorporated node modules and npm into

13:20

Speaker 1: this already perfect app. Hooray! Uh next step is we're going to take the CSS file and we're going to uh pass it through CSS preprocessors. Uh for this one we're going to be using SAS. Uh The uh other common ones, less is uh the syntax of less, if you've learned SAS uh or less, learning the other one it will be uh minutes of reference. Uh stylus. A little bit a little bit different, but uh still very similar concepts. Basically just uh all three of these are a very smart person having decided how they want uh what's Capabilities should have initially been built into CSS and then writing programs to enable that sort of syntax.

14:06

Speaker 1: Let's look at our initial CSS file. You don't actually have to uh read it here, but I've I've divided up the file into two different parts. Uh you can kind of see that there Because it's such a limited file, there aren't too many issues with it, but we can maybe see some areas for improvement. Um our selectors. Uh for the button we have a whole host of different items that are referencing button, button hover, button fo inner focus hover, button image, button button text. Same thing over there too, referencing different parts within wrapper, wrapper H1, and wrapper attribution. The ability to nest those would be kind of nice. Another thing that, for example, we're referen we are referencing colors in multiple places.

14:52

Speaker 1: You can see up there the BBDDFF as well as over in the button hover state we use the same color. Uh it would be less error prone if we could store those in variables. Okay, so uh how do you do it? First, oh uh yeah sorry. Uh that's why you might want to do this. Having rewritten the file within uh SAS syntax, it will look relatively similar to the point w to the point where someone who hasn't taken the time to uh learn SAS would still be able to pick up on what it's doing. Uh the main focus here is on nested selectors. You can see that uh the button element on the right side is uh taking away from the need to reference button hover, button most uh focus

15:38

Speaker 1: enter, button image, and button text. Uh and you can also see that we're now using a light blue variable which we declare uh higher up in the file. Okay. Um once once you have run uh once you've uh created this. The or even before you've created this, one uh very useful thing about CSS preprocessors is that anything that is valid CSS is also going to be valid SAS or valid less. You can pass a your normal CSS files through a preprocessor, and if you so desire, the uh if you wanted to do nothing but Uh pass it through for practice or pass it through because you wanted a very uh indirect way of minifying your CSS file, those are totally valid ways of doing so.

16:28

Speaker 1: Um okay. I said in the beginning that jumping into front-end development doesn't uh have to be an all or nothing thing. Adding these tools in one by one uh and recognizing the pain points that they bring you uh can be a very modular uh process. Um this next one is a good example of that. Uh browser sync is a uh utility that the React and Vue and Angular world uh they take advantage of that we can have within the Django world as well. Um I'll see if I can get this up and running. Uh show you a nice little fun example of hot module reloading here. Bring my terminal windows go. Do

17:14

Speaker 1: there we go Oh cool, yeah, you can see that. Sorry, I forgot my flags. Cool. So let's grab this command that I was running earlier today. That started the run server. Okay, and just for fun, now let's crack open another terminal here. Resonating.

18:00

Speaker 1: And let's edit. So uh what we're doing right here is you can see we're running on port 3000 instead of port 8000. I also have Fort 8000 running. Uh that is the default Django run server, but uh the lowest impact way I found to get browser sync and hot module reloading uh which It's not technically what we're doing here, but getting uh faster reloading into your projects uh is to run browser sync within a proxy flag. So when we do that Now if for example I were to take this uh CSS file and let's say I just wanted to make it change change the color. I saved the CSS. I changed the CSS. I changed the CSS

18:46

Speaker 1: file. I don't change the CSS file. I miss my keyboard, guys. And uh you don't need to reload the page anymore. This can be a very useful tool for kind of iterative uh development. If you decided, well, let's see how the page would look with maybe a little bit more padding. Do I like that? Yeah, let's see how we like it with even more padding. Yep, it uh it makes your front-end development process uh quite a bit faster. So uh nice not not a game changer, nice little tool to have Okay, let me get back to my presentation.

19:36

Speaker 1: Okay. Next step, uh we are gonna add Webpack into this project. Uh Webpack is a build process manager. It uh accomplishes similar goals that you would see within something like Browser say uh BrowserFi, Gulp, or Grunt. Uh like the uh more basic libraries that we were using earlier, it is installed via npm. What it is useful for is it bundles different front-end assets together. So for example, you can divide up your JavaScript files into separate files, which is what we'll be doing as part of this step here. It also helps you manage your non-code dependencies. You can keep track of your font files, your images, uh, different resources that are maintained by the front end of the application, and uh gives you a nice way of mod of declaring what happens when you're building out your project.

20:25

Speaker 1: Um one of the things that always bothered me when I was writing JavaScript in the old way was the global declar declaration of variables If I wanted to break my code up into multiple files, uh I needed to write my code with uh keeping in mind the ordering of script tags rather than uh keeping track of what delineations and breaks within my code made sense to me. That struck me as a limitation imposed by the browser and it is something that Webpack makes a little a little bit easier. The uh the appeal to a Python developer is also pretty basic here, where Uh in Python, everything that we're going to be importing into a file is uh everything that we want to use in a file uh

21:10

Speaker 1: is imported at the top of the file. Our imports become authoritative, trustworthy sources of truth on where different pieces of code are being used throughout the code base. If we're not sure if a library is in use, we can search our code for the imports. If all of your JavaScript code is built out with JavaScript imports, managed and bundled through Webpack, then you get the same peace of mind within your own project. You no longer have to worry about breaking something when moving around script tags because your JavaScript has independent sources with uh because each of your JavaScript files is an independent source of information that has everything that it needs. I will say um what I mentioned before about adding different pro

21:56

Speaker 1: different uh Frontend utilities to a project applies maybe twenty times for Webpack. If you are concerned about the complexity for a uh new for a person who's new to front-end development uh evaluate within your project whether Webpack is right for you. The benefits are, you know, can can be great. Uh it is added complexity. And Uh we'll walk through the example of how to incorporate this into our much smaller app. For those of you who have, for example, say hypothetically if you had like 3,000 line jQuery files that you're too afraid to touch at work. then uh you can maybe see how this be this be problematic. That was uh personal experience.

22:41

Speaker 1: We are currently sorting through a 3,000 line jQuery file that we're also too afraid to touch because it is Used by everyone. Um so how do we use it? Uh the first thing we do is we make a webpack. config. js file. This uh was the simplest one that I could think to write. What we're doing right here is we are taking a single file called uh index. js contained within a source directory. And we are outputting it to a file called bundle. js, which is going to live at the root of our project within a folder that we are calling dist Uh both the convention of storing your output within DIST and keeping all of your source files within a folder called SRC are conventions that we are borrowing graciously from the node community.

23:31

Speaker 1: Okay, uh first step is uh you install Webpack as well as the command line interface through npm. Uh You find no vulnerabilities and you're good. While doing node development, you do get scarily good at ignoring different warnings, but I've been told by very smart people that this one is totally fine for me to ignore. Uh once we've done sorry once we've done that, uh we can look at our uh package. json file, which uh contains new references to the Webpack and the Webpack CLI dev dependencies. Um While you can structure a requirements. txt file in Python however you'd like, uh not everyone follows the convention of dividing up dependencies into requirements and test requirements or requirements and dev and staging

24:17

Speaker 1: requirements. uh in the in the npm world uh that is a little bit more clearly delineated where you are Where if you install things with the dev flag, they are installed into a totally separate dependency. And the advantage of that is that then Node is able to figure NPM is able to figure out while you're sorry, Webpack is able to figure out while you're bundling up your project whether or not uh which projects to incorporate into the bundle. Um the other thing that I'll reference over here is that um in npm land the command line utility gives you access to npm run blank. If you add anything into this scripts JSON part of the JSON right here, these become commands that are aliased out.

25:04

Speaker 1: to uh different parts of to whatever system commands you might w want to run. So this gives you a very nice snifty interface for being able to specify all of the commands that you're running as part of your project. Uh in this example, when we run npm run build, what I really want it to do is to run webpack with the flag of mode set to production. And uh you can all see a test flag there. Uh I have not incorporated any test coverage into this app, and I'm very sorry about that. Uh so let's see how this works. Um in the beginning of this, uh you can see that I do not have a dist folder. I run npm run build. Webpack does wonderful magic for me, which takes in sorry

25:50

Speaker 1: which takes in my source index. js file and it outputs it into uh the disk folder. As a precursor to that process, I have copied over my uh JavaScript from the original app, the quote. js one, that very helpfully and informatively tells people that they have not looked at the quote for long enough. and uh moved it into this source directory, which now lives in the dist directory because webpack The next part of incorporating this into my Django project is that I list it as a static file directory. Now everything that lives within our final build directory, uh aka dist. is going to be referen able to be referenced from within static files. I can then incorporate that into my template.

26:37

Speaker 1: Uh I can replace the both the reference to our self-hosted jQuery and my custom quote. js JavaScript with a single tag for bundle. js because now bundle. js contains everything that I need. If you care about uh you know uh and uh to some extent everyone should care, the if you care about the size of the uh JavaScript that your application is generating because you're in an environment where people don't have time to wait around for, you know plus one second for the page to load. Uh this is a great way to bring down the size of your assets and uh can be compartmentalized to divvy up the uh the JavaScript files so that they're only downloaded when they're needed. And then if not, uh

27:22

Speaker 1: if you don't care if you truly don't care about the uh download size and performance of your uh front-end application as far as uh making big files is concerned, this is still a better way to develop uh your No longer relying on globally scoped variables scored within uh stored within the web browser. You don't have to worry about if in some random file you decide to declare $ as a variable that jQuery would break. opens up to a little bit more security that on the back-end side of things we take for it granted. Uh talking about how I break up break apart this file. This is the uh the function that I had previously that tells me whether or not a user has waited for long enough. It is a pretty basic function that just takes in uh the time that the user loaded up the page, figures out

28:10

Speaker 1: the JavaScript equivalent of a date time time delta and then uh returns back whether that has it has been ten seconds. Uh the interesting part here is this export fun on the other side of things. That is a uh newer uh part of JavaScript uh that is incorporated within uh both Webpack and Node itself. uh to be able uh to enable you to split your files up across different imports. By declaring an export on an individual function right here. Within this next function, I'd be able to use JavaScript import syntax to specify that I want that function to be imported. Uh I'm also saying that I am going to request uh jQuery as available at the dollar sign variable so that I can keep most of my code to be similar.

28:56

Speaker 1: Uh having done this, you can see that my code is uh it wasn't it was never unmanageable, now it is even more manageable. So nice to have Um let's look at this now that my JavaScript lives across two different files. Uh you can see that what MP what Webpack is doing when I build this w when I build this together is it is taking both my index. js and my utils. js and one mysterious hidden module, which I don't just it's it's jQuery, dude. You know it's jQuery Uh and it is outputting all of that into bundle. js. The end result is that I have a bundle. js that is b basically the exact size of minified jQuery plus a little bit for the code that I've written.

29:43

Speaker 1: Um yep. The end result is a smaller and faster uh download for the end user and a better, safer development experience for us. Hey! Alright, last uh tool that we're gonna be incorporating as part of this. Uh I'm going to show you how to put a little React component into our app. Uh because I was worried that anyone thought that we had not over-engineered this enough that The uh I don't think I've actually shown you the uh app in action yet, but basically if you uh have the app running oh look it's still got nice beautiful uh pink background now instead. Um The app rot loads up a different one, and then if I click give me another one, it tells me this very irritating, aggravating message.

30:30

Speaker 1: Two Mississippi three Mississippi four Mississippi five Mississippi six Mississippi 7 Mississippi Mississippi Okay. Now it gets me another quote That's right. He was a contemporary of Einstein, by the way. Uh lived in the early 1900s. Anyway, so this button right here, the gimme another cowboy button, is the one that we are going to be replacing with uh a React component. Uh at this point, most people have heard about React. Uh it is fancy. It's nice. Um it is a libr it is a JavaScript library for building user interfaces. It is written using an HTML JavaScript-y uh hybrid syntax called JSX.

31:17

Speaker 1: And it works by creating different components that live on a web page. Uh a React app begins by having one single root document uh for each part of the React app that you're gonna have. For example, you could have uh two different divs on your page with different IDs and load two totally separate React applications into either of those. But the way that uh React uh declares itself is that you just specify it I'm giving you a div on the page, React, this is your job. This is everything else outside of the page. Don't worry about it. All you have to do is make sure that that thing looks, be looks, contains, and behaves according to user interactions

32:02

Speaker 1: exactly as expected. Let's see. If React uh if you are evaluating whether to uh put React into your project, um I will say that there are a couple of signs for when React might be a good fit. Uh if a user is doing something on the page that is changing five different values and each of those has a a different vanilla JavaScript or jQuery function that you've written, uh keeping track of those using a React might be a little bit more efficient. If you are trying to do an incredibly complicated user interaction, you know you're you need to keep track of the state that that a user has uh done within within that the state of all the things that a user has done.

32:48

Speaker 1: Then uh React or Angular or Vue. Personally I like Vue. Vue is my favorite uh UI framework. Uh those can be uh pretty those are pretty good signs for when you might want to incorporate React into your project. And then uh finally if You can uh maintain pretty much everything using uh API calls back to a server. Every user interaction is stored on is stored on the server and then either uh you know Django JSON views or totally re-rendered content can be returned from uh API endpoints. Those are all totally fine ways to build out your application. But if you are uh struggling to maintain the state of a user's interactions upon page load, one

33:36

Speaker 1: potential solution to this could be to do away with the the very concept of page loads and make it so that your React App is aware and benevolently keeping track of your user's interactions at any given point. But Also, maybe not. Uh React is not intuitive. React is uh hard to learn, and that applies for most library most UI libraries out there. Uh We had we had backbone installed on an app at work for a while and uh we everyone just kind of avoided it like the plague. You know, we thought every time it's working we don't go near it. Uh we and people just didn't want to take the time to Learn how to use it. It is mental and cognitive overhead, and it may not suit your purposes properly.

34:24

Speaker 1: That applies so many times over to the uh concept of an app that just displays a random Will Rogers quote. This is uh very much an overkill app, and it would be totally silly to build a React component to do that. But I like silly things, so we're gonna do that. Um we are going to replace that little button on the bottom with a React component. Um First thing we're gonna do is install two libraries. The first is React, uh, which is the actual library that we'll be building out our components with And the second is React DOM, which is the library that React uses for latching on to different parts of the of the DOM, the document object model used within your browser. We are

35:09

Speaker 1: going to be writing this using that uh HTMLE, JSE , weird language JSX that I was talking about before. Uh your browser doesn't know how to read JSX, so this is going to uh we are going to need to also install another library called Babbel, which is uh and accompanying libraries for tying it into React. all of the above our utilities for making it so that when Webpack encounters a JavaScript file written with written with React, it is a it is going to be able to process that into our dist folder and produce something that our browser Is actually able to understand. Uh this is what our new Webpack configuration looks like. The uh everything below line eight is new here. The way that we've configured Webpack in this instance is to say that anything containing JS or JSX

35:59

Speaker 1: is going, except for things in the node modules directory, is going to encounter the following rule. uh send it through the program known as babbel loader uh with the preset of react. That is us saying every time you hit a jsx file, send it through Babel with React. Uh let's see. The next thing we do is we go back into our template and we wipe away everything that we had there previously for the uh button. This uh line 20 is now the exclusive and sole domain of React. React is going to be helping maintain the state and the display of this at any given time. And uh we don't Django templates are no longer gonna have to worry about whatever is not in there

36:44

Speaker 1: And this is what a React component looks like. This is uh we are importing React using the uh similar syntax that we saw before uh in our newly modularized JavaScript. Uh we are creating if for uh pass over the export default for a moment and this looks almost a little bit pythonic to say we are we have a class that is extending another class and then it contains the following attributes Uh export default just enables us to load this in from a different file then. Um the uh React component. uh is initialized with a state which we are declaring here. We're telling it that uh you're gonna start off with a state equal to uh a JavaScript object containing the

37:31

Speaker 1: a key of start and a value of when the the a date object for when the object was created. And we are going to tell React that you are going to be using a method called handle click. Within the render function, we this is what uh JSX looks like. You can see it's almost excl almost entirely HTML. The main differences are that because we are not going to be using uh Using the click keyword op uh we're not able to actually use on click because it is a reserved keyword. Uh we are instead uh declaring it with this kind of bumpy syntax. Uh And then we are able to actually pass in what is a an expression that is evaluated as JavaScript here.

38:17

Speaker 1: Um anything within curly braces in a React component is understood to be JavaScript. So that's kind of a You know, I think when you're working in the Django templating language, this uh idea of being able to or you know, Django templating language or PHP or really any uh handlebars in JavaScript. Being able to drop into code is something that we take for granted, but uh it is nice to be able to have one way of doing it and React. uh as well as view components and angular components all give you a really nifty hint uh syntax for doing so. And then finally we are declaring uh I'm I've uh declared this React component as a class-based component, so it has a method called handle click. Uh when this button is clicked The handle click method is called. What is the handle click method?

39:03

Speaker 1: It's basically the same thing as we were seeing before. The uh end result here. The end result here is that uh we have a component that does exactly the same thing. Um and I think the only thing that I did not uh properly show you there The other thing I forgot to show you here is within our source index. js file, uh

39:49

Speaker 1: how we are using the React DOM method. Uh The our initial file, we were able to comment out the uh event listeners, which would have otherwise made the event trigger twice because it does still have the ID. Uh so we commented all that out. And then we import React, both React and ReactDum at the top of the file, and then tell ReactDumb, I have made something called a next button component. And I want you to load that into the element note with the ID of next button, which if you'll remember from quotes and plus is this thing that we have told it to stop caring about right here. So that is how we tie in our Django templates into a React component.

40:39

Speaker 1: Because I have been talking a lot about React because it's a useful uh way of uh getting people excited about front-end development. I have not uh mention view quite as much, but if you were curious about how to build this out as a view component, uh it would look like so. There. Um Vue has a Weird uh definition of separation of concerns. Uh with React everything kind of lives jumbled together. In Vue, everything also lives jumbled together in the same file but within separate tags Uh you can see that that template tag at the top of the file is analogous to an HTML import or to an the HTML portion of your file. The script tag is uh analogous to the user user experience in the JavaScript of your file.

41:25

Speaker 1: And that very tiny non-existent uh style tag at the bottom of the file is useful uh is where you could put your CSS rules Um I like that this allows you to store all of your component, everything about a component within one set package. I don't have great internal memory. Uh my head does not keep things in it very long. So the ability to think of my code as You have this big application and it's made of littler stuff that happens here, and you don't have to worry about bleedover from those is valuable to me. So what I like about this single line, uh single file view component is that this is my button.

42:11

Speaker 1: There are many like it, but this is my button. And uh yeah, you can see kind of the syntax is uh not it's not it's not intuitive, you have to learn it, but uh once you do, uh And now get to be that person who tells you, you know, if you have not done any front-end development before, like trust me on the other end of it, it it does make sense. Oh right, I killed my presentation. Uh there we go. Oh. You know, the last thing I had was a thank you slide anyway, so um I'm gonna I'm gonna make this my thank you slide

42:58

Speaker 2: Thank you, Robert. This was really impressive and not over engineering at all. I really like this. This is I could follow it along and this was really helpful. Thank you. Um other questions Coming once? Yes. Uh it's not really a question. This is not really a question. Could I ask you if it's a comment or something, could I ask you to sort this out afterwards? I I unless you have a questi actually question. Okay.

43:36

Speaker 1: If you can jeopardify it please. Uh what

43:39

Speaker 3: do you think about so talking about over engineering, I had the pleasure of getting to use Redux. The first time I use React , OSF turned on. No it didn't. Sorry about that. Uh I had the pleasure of overengineering my first React app because the first engineer chose Redux for like a chart-based small app. And it was a huge lane down that hole. But how do you f figure out when that over-engineering point is applicable? And then state management. There's so many options for like all these different things. So it's without the experience, it's really hard to tell.

44:23

Speaker 1: Yeah, definitely. Um so the the question was uh when regarding specifically the concept of state management, when do you figure out if over engineer w if you are over engineering it by incorporating Additional libraries, uh for example Redux or Vuex or uh I don't know with Angular. I guess you can use Redux with Angular. Oh, cool. Thank you. Uh yeah, MobX. When is it uh over-engineering to incorporate those into your project? Um I didn't I deliberately did not talk about Redux during this. Uh it is An incredibly useful concept. Basically the idea is that your components not uh they do manage their own state, but they also are have a way of interacting with your application's global state.

45:11

Speaker 1: So for example, like if you think of Facebook, the go-to example is uh someone checks a message and then suddenly the counter of number of unread messages needs to decrement by one. and the message needs to show a different CSS class and on the other side of the page that message needs to no longer be bolded. Those all had to be would otherwise have to be passed back and forth between different components. Uh keeping a global state store can be a very useful way of having one single source of truth for what has happened in your application. Uh my answer for the over-engineering aspect is one Practice comes with experience, go for it. Uh but two, if you are if you have anything where the user can get themselves into a state

45:57

Speaker 1: Where there are a lot of things going on on the page, that's probably a good candidate for a state management library.

46:04

Speaker 3: Cool. Thanks.

46:07

Speaker 4: Hello, thank you very much. This was very enlightening. Um You have been the third speaker today, I believe, to mention WebPack as a tool for managing uh node uh build and dependencies. Uh you have been the first as far as I noticed to notice that it wasn't the first such tool that there was Grunt and Gulp and uh other things and uh as a a primarily backend developer who shies away mostly from the front end because uh the landscape there keeps changing all the time I have to ask, are we there yet? Is is WebEx it. Um

46:54

Speaker 1: I one thing that I neglected to mention throughout this whole talk is that the biggest asset for me has been that on my team we hired a uh senior front-end developer who has been an incredible learning resource. And he is a huge advocate of uh u using Gulp as the build process manager. Uh I think I don't think it's I don't think it's a there yet thing. I think it is a code versus configuration thing. If you prefer to have a standardized set, a way of specifying within your Webpack file These are the things that I want to do, and I want it to be one JSON file, and I want it to ha I want there to be a right way of doing things, and please don't make me think about this anymore and let me go back to coding. then Webpack is a good answer for that.

47:40

Speaker 1: If you do want to dive deep down into the way that your build process operates and maybe even add some custom configuration using JavaScript, that then Gulp is a great tool for that. I say that reluctantly because it is truly confusing to have so many tools out there, but uh for me personally, I fall into the school of I just need I have other things that I'd like to be thinking about and Webpack works totally great. Uh it's the one that you get by default with CreateRact app and it plays nicely with View, so uh

48:26

Speaker 5: uh JavaScript and images and CSS files and grunt is like a task runner so it's usually used to execute Webpack. Are there like What other uh projects are that it are a real alternative to Webpack and not just like used to run it?

48:43

Speaker 1: That's true Uh Webpack does, uh one of the main selling points of Webpack is that it does uh say we will not only be managing your JavaScript, we'll be managing all of your front-end assets, your C your CSS, your images, your fonts. um and sending those through a uh standardized pipeline. Uh there are there are tools that you would then incorporate into Gulp that allow and I'm sorry, I've never worked with grunt so I'm not gonna uh talk about grunt so much, but uh you can incorporate parts of uh different uh tools into gulp so you're no longer building out a full-on monolithic solution for how you can manage your your dependencies. uh sorry your build process instead you are telling uh from this gulp file conditionally run this different command

49:29

Speaker 1: Uh if you're looking for the one-shop solution, which I think is is not a disparaging thing. One-stop shops are great. uh then webpack is uh a pretty good solution for that. But there I have not encountered something that a smart person couldn't also do in Gulp.

49:49

Speaker 6: Thank you for your excellent presentation. Imagine that you are able to make me understand it. It is extraordinary. However, even your extraordinary work in bringing all of that front-end tools to Django, you maintain the approach of the monolithic Django. What's your view on decoupling the back end of Django using an API interface and using React or whatsoever as a completely different approach?

50:21

Speaker 1: Yeah, the uh the dirty secret of this presentation is Oh I deleted it, never mind. Uh I had some I had some Django Rust framework serializers in here as well. Um It's when I first started doing this, I almost felt a little dirty for not doing j the things the Django way. Uh the the basic the question is uh using React and Vue it is possible to uh decouple your applications such that you no longer need the Django templating language. uh you don't need to use Django routing anymore and you you basically just turn Django into a headless system for building out APIs

51:07

Speaker 1: and then you build out uh your application with React and View or React View or Angular Um that architecture makes a lot of sense in a lot of places. Uh the Django templating language is incredible and it is great for many tasks, and I would evaluate whether the additional complexity of Reactor View, especially for us people who know Django, uh, is worth it. Um and the answer to that is gonna o oftentimes be no. But Uh you can maybe imagine an app that has very complicated user experience uh intricacies to it, in which case uh We don't have to give up our full stack. Luckily, Django is the best way of encountered for building out an API.

51:56

Speaker 1: Django graphene is a great way of building out GraphQL API endpoints that uh React developers just seem to love for some reason. Um but I think that it's the decision to decouple your app is uh one that adds a lot of complexity to your project and should be taken with a grain of salt. but it is a totally viable one and once you are if you are comfortable with a front-end uh development library and you're comfortable with a uh backend web framework then you know world's your oyster. You can build you can build anything.

52:32

Speaker 2: Alright. Um are there any c more questions in the room or on the map? No? Then thank you Robert. Again.

Questions this talk answers

How do I add npm and frontend dependencies to a Django project?

Install Node, run `npm init` in the project directory, and use `npm install` to add libraries. npm records dependencies in `package.json` and `package-lock.json`, much like pip tracks Python dependencies.

Discussed at 9:27

Can I serve node_modules as a Django static directory?

You can use it as a simple stepping stone while learning npm, but it is not a good long-term approach: `collectstatic` will copy thousands of files. Once you are comfortable with Webpack, bundle the assets instead.

Discussed at 11:47

What does Sass add to regular CSS?

Sass adds features such as nested selectors and variables, making repeated selectors and colors easier to manage. Existing CSS is also valid Sass, so a normal stylesheet can be introduced gradually and passed through the preprocessor unchanged.

Discussed at 14:12

How can I make frontend development in Django reload faster?

BrowserSync can proxy the Django development server and refresh the page when frontend files change. This lets you see CSS changes immediately without manually reloading, which speeds up iterative styling.

Discussed at 16:28

What is Webpack useful for in a Django frontend?

Webpack bundles frontend assets, lets JavaScript be split into modules with imports and exports, and can manage related resources such as fonts and images. It also produces smaller, more efficient bundles and avoids relying on globally scoped variables and script-tag order.

Discussed at 19:36

When should I use React, Vue, or another frontend framework in a Django app?

These tools are a good fit when interactions change many parts of a page, require tracking complicated user state, or would be easier without repeated full page loads. They are usually unnecessary for simple interactions, and they add significant learning and cognitive overhead.

Discussed at 32:02

How do I connect a React component to a Django template?

Reserve an element in the Django template for React, then use ReactDOM to render the component into that element by its ID. Webpack and Babel process the JSX, while Django remains responsible for the surrounding page.

Discussed at 39:49

When is Redux or another state management library worth using?

A global state store is useful when many parts of the interface need to respond to the same user action, providing one source of truth. A page with many simultaneous states and interactions is a strong candidate; otherwise, adding such a library may be over-engineering.

Discussed at 44:23

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 Europe