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

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

Open full transcript Markdown

Transcript

8,414 words · auto-generated · en Show transcript

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

Robert Townley

Okay, hey everybody. Yeah, I think a lot of people don't feel super good about the front end part. And that's what I'm here to today to talk about. 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. Hi everybody. How are you? How are you all doing today? Like collectively, you know. Sufficient levels of caffeination in the room, people, you know, feeling reasonably spongy in their brains right now.

Okay. 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, bicycling for fish, and of course creative writing for professional wrestlers. I am I'm very grateful to 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. It is a huge vote of confidence that over the next 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.

This presentation is sorry. This presentation is geared towards a reasonably narrow band of band of people. If you're not yet super familiar with HTML, CSS, and JavaScript. This is there's gonna be parts that are gonna be confusing for you. 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. That is totally reasonable too. Personally, I put myself somewhere in the middle. I've had some successes 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

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. It reminded me of 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. Model template view architecture just made fundamental sense. 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. The better way of doing things just clipped. It wasn't that way when years later I was trying to move beyond jQuery into the world of modern front-end development.

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? Why do I need these ten different random libraries to perfectly have the moon align to play nicely with each other. 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 really confusing thoughts and I think they stommied my process because I was trying to eat an elephant doll in one bite

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

The airport in Tulsa, Oklahoma is named after one of Oklahoma's most famous citizens, Will Rogers. Not to be confused with Fred Rogers, the man who was behind Mr. Rogers' neighborhood, Will Rogers was a cowboy philosopher. He did perform he got on horses and spun lassos and performed and did tricks while just stream of conscience talking about what was on his mind and eventually people 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.

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. Anyway. I thought of him when it came time to give this talk because the idea of a thinking cowboy. 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 application that we'll be working with. I have on my local run

server over here. Yeah, he's great. I have this a application running on my local run server, which we will 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 front-end techniques. Okay, so let's get started on looking at the actual Django project. The app itself is pretty simple. It has one app called Quotes, 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.

The view, going back to the view, the view itself 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 custom CSS style sheet to make the app look a little bit better. We have a CDN supplied jQuery, and we have a JavaScript file that contains all of our user interactions. 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 telling you to please wait more for the next the next update.

If the user has waited, then window. location. reload is called and the user gets a new randomly generated quote. Pretty simple and 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 the first thing that I want to mention about this app is that this app is perfect. 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.

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 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 latest, shiniest toy.

Okay, the first thing we're gonna do is add 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 runtime, sorry, the back-end runtime environment that makes back-end JavaScript possible. NPM is the package manager for Node. 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. If your only front end is d dependency is jQuery, similar with packages and apps that you're developing in the future. Even if you aren't using Tween for animation, moment. js for time and Axios for making asynchronous requests,

having a requ having a package. json file in your project does a lot to give new contributors to your project an understanding of what it is that you'll be doing. Okay, so how do you use it? To get started with it, you have to first have an up-to-date version of Node installed on your computer or server, and then you initialize it from the project directory with npm init. From then on, any commands you run to install the library, 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 let's add a couple of dependencies into our project first.

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 file has been modified. I don't include that, sorry. 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. Adding in another library called normalize. css, we will be incorporating both those into the project. Let's see. Looking inside of node modules you can see that that that is where the actual jQuery installs have taken place. This is kind of a quick and dirty way of getting node modules into

A Django application, and a lot of my teammates who are better front-end developers than I have 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 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 dip your toes into front into keeping track of your packages within pac within npm, this is as good of a stepping stone as I had found.

So within settings. py we declare node modules as a static directory. 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, newbies who are coming into the project will be able to understand the different JavaScript dependencies that you're using. You're keeping track of them for yourself, and you have more independence for later on pursuing different parts of the project. We have successfully incorporated node modules and npm into

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

Let's look at our initial CSS file. You don't actually have to read it here, but I've I've divided up the file into two different parts. 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. Our selectors. 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 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.

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

enter, button image, and button text. And you can also see that we're now using a light blue variable which we declare higher up in the file. Okay. Once you have run once you've created this. The or even before you've created this, one 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 if you wanted to do nothing but pass it through for practice or pass it through because you wanted a very indirect way of minifying your CSS file, those are totally valid ways of doing so.

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

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.

And let's edit. So 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. That is the default Django run server, but the lowest impact way I found to get browser sync and hot module reloading which It's not technically what we're doing here, but getting faster reloading into your projects is to run browser sync within a proxy flag. So when we do that Now if for example I were to take this CSS file and let's say I just wanted to make it change the color. I saved the CSS. I changed the CSS. I changed the CSS

file. I don't change the CSS file. I miss my keyboard, guys. And you don't need to reload the page anymore. This can be a very useful tool for kind of iterative 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 makes your front-end development process quite a bit faster. So nice not a game changer, nice little tool to have Okay, let me get back to my presentation.

Okay. Next step, we are gonna add Webpack into this project. Webpack is a build process manager. It accomplishes similar goals that you would see within something like Browser say BrowserFi, Gulp, or Grunt. Like the 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 different resources that are maintained by the front end of the application, and gives you a nice way of mod of declaring what happens when you're building out your project.

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, I needed to write my code with keeping in mind the ordering of script tags rather than 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 appeal to a Python developer is also pretty basic here, where in Python, everything that we're going to be importing into a file is everything that we want to use in a file

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 because each of your JavaScript files is an independent source of information that has everything that it needs. I will say what I mentioned before about adding different pro

different Frontend utilities to a project applies maybe twenty times for Webpack. If you are concerned about the complexity for a new for a person who's new to front-end development evaluate within your project whether Webpack is right for you. The benefits are, you know, can be great. It is added complexity. And 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 you can maybe see how this be this be problematic. That was personal experience.

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. So how do we use it? The first thing we do is we make a webpack. config. js file. This was the simplest one that I could think to write. What we're doing right here is we are taking a single file called 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 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.

Okay, first step is you install Webpack as well as the command line interface through npm. 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. Once we've done sorry once we've done that, we can look at our package. json file, which contains new references to the Webpack and the Webpack CLI dev dependencies. While you can structure a requirements. txt file in Python however you'd like, not everyone follows the convention of dividing up dependencies into requirements and test requirements or requirements and dev and staging

requirements. In the in the npm world 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 which projects to incorporate into the bundle. The other thing that I'll reference over here is that 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.

to 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. 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 you can all see a test flag there. I have not incorporated any test coverage into this app, and I'm very sorry about that. So let's see how this works. In the beginning of this, 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

which takes in my source index. js file and it outputs it into the disk folder. As a precursor to that process, I have copied over my 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 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, aka dist. is going to be referen able to be referenced from within static files. I can then incorporate that into my template.

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 you know and to some extent everyone should care, the if you care about the size of the 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. This is a great way to bring down the size of your assets and can be compartmentalized to divvy up the JavaScript files so that they're only downloaded when they're needed. And then if not,

if you don't care if you truly don't care about the download size and performance of your front-end application as far as making big files is concerned, this is still a better way to develop your No longer relying on globally scoped variables scored within 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. Talking about how I break up break apart this file. This is 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 the time that the user loaded up the page, figures out

the JavaScript equivalent of a date time delta and then returns back whether that has it has been ten seconds. The interesting part here is this export fun on the other side of things. That is a newer part of JavaScript that is incorporated within both Webpack and Node itself. To be able 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. I'm also saying that I am going to request jQuery as available at the dollar sign variable so that I can keep most of my code to be similar.

Having done this, you can see that my code is it wasn't it was never unmanageable, now it is even more manageable. So nice to have let's look at this now that my JavaScript lives across two different files. 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 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.

Yep. The end result is a smaller and faster download for the end user and a better, safer development experience for us. Hey! Alright, last tool that we're gonna be incorporating as part of this. I'm going to show you how to put a little React component into our app. Because I was worried that anyone thought that we had not over-engineered this enough that The I don't think I've actually shown you the app in action yet, but basically if you have the app running oh look it's still got nice beautiful pink background now instead. 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.

Two Mississippi three Mississippi four Mississippi five Mississippi six Mississippi 7 Mississippi Okay. Now it gets me another quote That's right. He was a contemporary of Einstein, by the way. 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 a React component. At this point, most people have heard about React. It is fancy. It's nice. It is a libr it is a JavaScript library for building user interfaces. It is written using an HTML JavaScript-y hybrid syntax called JSX.

And it works by creating different components that live on a web page. A React app begins by having one single root document for each part of the React app that you're gonna have. For example, you could have two different divs on your page with different IDs and load two totally separate React applications into either of those. But the way that React 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

exactly as expected. Let's see. If React if you are evaluating whether to put React into your project, I will say that there are a couple of signs for when React might be a good fit. If a user is doing something on the page that is changing five different values and each of those has a different vanilla JavaScript or jQuery function that you've written, 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 done within that the state of all the things that a user has done.

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

potential solution to this could be to do away with 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. React is not intuitive. React is hard to learn, and that applies for most library most UI libraries out there. We had we had backbone installed on an app at work for a while and 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. 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.

That applies so many times over to the concept of an app that just displays a random Will Rogers quote. This is 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. We are going to replace that little button on the bottom with a React component. First thing we're gonna do is install two libraries. The first is React 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

going to be writing this using that HTMLE, JSE, weird language JSX that I was talking about before. Your browser doesn't know how to read JSX, so this is going to we are going to need to also install another library called Babbel, which is 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. This is what our new Webpack configuration looks like. The 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

is going, except for things in the node modules directory, is going to encounter the following rule. Send it through the program known as babbel loader with the preset of react. That is us saying every time you hit a jsx file, send it through Babel with React. 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 button. This 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 we don't Django templates are no longer gonna have to worry about whatever is not in there

And this is what a React component looks like. This is we are importing React using the similar syntax that we saw before in our newly modularized JavaScript. We are creating if for 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 export default just enables us to load this in from a different file then. The React component. Is initialized with a state which we are declaring here. We're telling it that you're gonna start off with a state equal to a JavaScript object containing the

a key of start and a value of when 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 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 the click keyword op we're not able to actually use on click because it is a reserved keyword. We are instead declaring it with this kind of bumpy syntax. And then we are able to actually pass in what is a an expression that is evaluated as JavaScript here.

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 idea of being able to or you know, Django templating language or PHP or really any handlebars in JavaScript. Being able to drop into code is something that we take for granted, but it is nice to be able to have one way of doing it and React. As well as view components and angular components all give you a really nifty hint syntax for doing so. And then finally we are declaring I'm I've declared this React component as a class-based component, so it has a method called handle click. When this button is clicked The handle click method is called. What is the handle click method?

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

how we are using the React DOM method. The our initial file, we were able to comment out the event listeners, which would have otherwise made the event trigger twice because it does still have the ID. 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.

Because I have been talking a lot about React because it's a useful way of getting people excited about front-end development. I have not mention view quite as much, but if you were curious about how to build this out as a view component, it would look like so. There. Vue has a Weird definition of separation of concerns. With React everything kind of lives jumbled together. In Vue, everything also lives jumbled together in the same file but within separate tags 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 analogous to the user experience in the JavaScript of your file.

And that very tiny non-existent style tag at the bottom of the file is useful is where you could put your CSS rules 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. 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, single file view component is that this is my button.

There are many like it, but this is my button. And yeah, you can see kind of the syntax is not it's not it's not intuitive, you have to learn it, but once you do, 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 does make sense. Oh right, I killed my presentation. There we go. Oh. You know, the last thing I had was a thank you slide anyway, so I'm gonna I'm gonna make this my thank you slide

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. Other questions Coming once? Yes. 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 unless you have a questi actually question. Okay.

Robert Townley

If you can jeopardify it please. What

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

Robert Townley

Yeah, definitely. So the question was 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, for example Redux or Vuex or I don't know with Angular. I guess you can use Redux with Angular. Oh, cool. Thank you. Yeah, MobX. When is it over-engineering to incorporate those into your project? I didn't I deliberately did not talk about Redux during this. It is An incredibly useful concept. Basically the idea is that your components not they do manage their own state, but they also are have a way of interacting with your application's global state.

So for example, like if you think of Facebook, the go-to example is 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. 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. My answer for the over-engineering aspect is one Practice comes with experience, go for it. But two, if you are if you have anything where the user can get themselves into a state

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

Speaker 3

Cool. Thanks.

Speaker 4

Hello, thank you very much. This was very enlightening. You have been the third speaker today, I believe, to mention WebPack as a tool for managing node build and dependencies. 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 other things and as a primarily backend developer who shies away mostly from the front end because the landscape there keeps changing all the time I have to ask, are we there yet? Is WebEx it.

Robert Townley

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 senior front-end developer who has been an incredible learning resource. And he is a huge advocate of u using Gulp as the build process manager. 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.

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 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. It's the one that you get by default with CreateRact app and it plays nicely with View, so

Speaker 5

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 projects are that it are a real alternative to Webpack and not just like used to run it?

Robert Townley

That's true Webpack does, one of the main selling points of Webpack is that it does 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. And sending those through a standardized pipeline. 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 talk about grunt so much, but you can incorporate parts of different tools into gulp so you're no longer building out a full-on monolithic solution for how you can manage your dependencies. Sorry your build process instead you are telling from this gulp file conditionally run this different command

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

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?

Robert Townley

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

and then you build out your application with React and View or React View or Angular that architecture makes a lot of sense in a lot of places. 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 is worth it. And the answer to that is gonna o oftentimes be no. But you can maybe imagine an app that has very complicated user experience intricacies to it, in which case We don't have to give up our full stack. Luckily, Django is the best way of encountered for building out an API.

Django graphene is a great way of building out GraphQL API endpoints that React developers just seem to love for some reason. But I think that it's the decision to decouple your app is 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 development library and you're comfortable with a backend web framework then you know world's your oyster. You can build you can build anything.

Speaker 2

Alright. Are there any c more questions in the room or on the map? No? Then thank you Robert. Again.

Presenters

Conference

DjangoCon Europe

April 10 - 14, 2019

Copenhagen, Denmark

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