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

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
come on hi everyone um so my name is Jack and I have - there we go well I'm a software developer from New York City and one of the reasons why I'm giving this talk is most of my recent projects three out of my last four recent projects were Django projects that also used react so I've dug deep into how the two can fit together and I really like how they fit together hopefully some has anyone here worked on any react projects okay so a handful so not a roomful of beginners that's exciting if you are a beginner I kind of geared this talk for people who know Django but haven't really used react yet or kind of just thinking about it and looking at it so I've been a Django user for over five years react user for about the last year or so a little longer than that and for what it's worth I don't consider myself to be any kind of expert on either of those things just someone who put in a lot of time working on Django projects and react projects and might have a little bit to share I'm gonna cry and talk fast if I talk too fast slow me down but um it's kind of a broad scope to this talk so I'm more worried about not having enough time than I am about like filling time I'll try and save some time for Q&A at the end but that's my contact info you can hit me up on Twitter or github if you have any questions that we didn't have time for today and also be around for the next couple days for the sprints so what are the goals of this talk the title of the talk really could be a crash course in react for people who already know Django the first goal is to understand what react does how react works because a lot of people are talking about it and people in the Django community some people have picked the tires on it some people have used it heavily but a lot of people haven't so it's kind of an intro to react for Django people and the goal is to build a mental map for react so that you know how to think about it it's going to take longer a 45-minute talk to build a good mental map for react but hopefully this will be a good primer we're going to become familiar with some of the key parts of a reactive project and learn how to set up a reactive project inside of a Django environment one of the other big challenges of learning react is that a lot of reactive projects and most of the react or plate examples use JSX and quote unquote new JavaScript es6 or ES 7 so we'll be diving into a little bit of that just so you know what you're looking at it's one of the things that can add some intimidation to learning to react and then finally we'll bring it all together by showing how Django and react can fit together in a project and we're actually going to start here a little bit at a high-level view before digging into the reactive part we'll look at the separation of concerns in a Django and reactive project that uses both so Django follows the MVC pattern for building user interfaces in the MVC pattern there are three parts the model the view and the controller and they're all interconnected this is kind of how they're interconnected the model updates the view the view is what's seen by the user the user can do stuff to manipulate the controller that this is based on the users interaction with the view and then the controller updates the model this is how Django works sort of there's a cool question on the Django FAQ page Django appears to be an MVC framework but you call the controller the view and the view the template how come you don't use the standard needs and the answer that Django gives is in our interpretation of MVC the view describes the data that gets presented to the user it's not necessarily how the data looks but what data is being presented it's sensible to separate content from presentation and that's where Django templates come in it's kind of a pedantic answer to that question but that's also part of the reason why I like it but what they're saying essentially is that in Django the part of the MVC is split into two things the view that you keep in views that py that renders data to your templates that actually are the view that the user sees so the map of an MVC from Django's perspective looks more like this where the model corresponds to your models PI file your views corresponds to your views PI they render data to your templates which is what the user sees he or she interacts with the templates to manipulate the controller which is kind of like the framework itself and the controller updates the model react fits here react fits where the templates are it replaces your Django templates and based on how the user interacts with those templates dispatches actions that then update Django that update the controller so this is what your MVC looks like in a react project the first thing about react to understand is that it's not a full MVC framework and it doesn't try to be if you use it in a Django project it'll fit where your templates used to fit it won't replace anything else in a Django project and keep in mind templates like it's the broad view of templates it's not just the templates files but also the files and packages that your templates use jQuery potentially CSS all of your JavaScript files that are imported into your templates so why would you want to do this Django templates work perfectly well why would you want to start stop using them and start using something that is significantly more complicated sorry about that that you have to learn from scratch and that's outside the Django ecosystem that you already know real well and love and the answer to that is maybe you don't maybe you don't want to use react and it would be over engineering to use react Django templates are perfectly fine for plenty of sites and we all know that because we've used that for plenty of sites they work but react lets you do certain things that would be really really hard to do if not impossible to do using just Django templates the first thing um that react templates let you do is it lets you turn your site into a single page app from the users perspective single page apps when they're built the right way they are faster they feel more modern it's something that's really been popular in the JavaScript community for a couple of years now and has been a little bit slower to become popular in the Django community and the Ruby community I know the channels are doing some work to be able to use templates to build single page apps but this is a big reason why react is deserving of a look another thing that you get with react is the ability to reuse parts of your code base for ios and android in addition to just your web app i'm not going to dive too much into this but it basically works like this your react their react templates are made up of components they're like building blocks that you assemble together to form your UI and each one of those building blocks does two things it performs some internal logic and then based on that internal logic it renders a chunk of what your users see it renders a chunk of UI with react native you get to keep the part of your templates that perform that logic and use them across platforms and then render out different code either HTML or iOS or Java based on the platform that the user is using and then finally this is probably the biggest reason why react as quote ons as because it has is it makes it much easier to manage and manipulate complicated state in most small projects there isn't complicated state the state is simple so there's not much to manage you can keep it all in your head more or less when you start working on a bigger project a managing state can become a real nightmare and I'm sure it's something that you've potentially run into that is the biggest selling point of react and the biggest thing that it makes much much easier so we're going to zoom in for a bit on the react part of this map so that you can understand and get a feel for that and we're going to zoom back out and look at how Django and react work together as part of a full system oh and one more thing since one since react is taking care of your UI your views are going to feed it raw data your view layer is really just an API layer react doesn't care what the rest of your stack is but using something like Django rest framework is it makes a heck of a lot of sense because then your views are just an API layer by default so the home page for react highlights a couple of things that differentiate it from other UI frameworks if you understand these three things you'll understand the fundamentals of react the first one we already talked about it's that react doesn't make assumptions about the rest of your technology stack react is your UI layer it provides a really good toolset arguably the best toolset for building your UI and it doesn't try to do anything else other than that the second point on the home page is that react is declarative and this one is a little bit tougher to grok react makes it painless to create interactive UI you might put an asterisk after the word painless it's painless once you go through the significant pain of like learning how to use it but once you understand that it is pretty painless it's actually very painless and yeah it's quite easy to use once you get it you design simple views for each state in your application and react will efficiently update and render the right components when your data changes so basically this means that when you use react your application state is kept separate from your done you declare what your Dom should look like given a certain state that your application is in and then when your application state changes your Dom changes as a result of that but react controls this change you don't control this change you only manage the state and what the state and what the Dom is supposed to look like given a state and then finally declarative views make your code more predictable and easier to debug it also makes your code a heck of a lot easier to test so how a declarative component compares with doing things the interpretive way with jQuery let's say you've got a very simple page you got a button and a div and you'll have two views where state one is the button shows the word hide and the div is their state two the button shows the word show and the div is not there this is how you code it out in jQuery I'm not including the actual HTML page where the Dom elements are declared but you have a JavaScript file you bind the click event to your button that click event will call a function every time it's fired that function is going to check what state the div is in whether the div is visible or not and then interpret from that state whether or not the div should still be show it'll interpret your application state based on what it sees and from that interpretation it's either going to show the div or hide it if the state is interpreted from your dot I know this is really bad jQuery by the light but yeah how you would do the same thing in react it's going to look very differently react uses components we already talked about that a bit and this file represents a single react component the easiest way to think about components is as a container for some part of your UI and this code looks it uses es6 so it might look a little bit different than the JavaScript that you used to see talk about that for just one second es six is the 2015 JavaScript specification it adds a whole bunch of stuff to JavaScript that never was there before it adds classes it adds modules so you could import an export javascript from files just like you can with Python packages it adds iterators and generators promises there's also an seven which is finalized last month but isn't really widely supported yet the point is that javascript is evolving and as it does it's becoming way more pythonic these are a handful of tweets that I found just of people noticing the similarities between modern JavaScript and Python my favorite is it turns out yes it's up in the corner on the right turns out es6 is basically Python with the added bonus of irritating front-end devs and this is me joking a year ago that by the time they get to es nine JavaScript and Python are going to be syntactically identical so back to the react component that we're looking at it represents a single section of your UI and it does two things inside the first thing that it does is it manages the state of this UI section and the second thing it does is it renders the component itself it actually renders the Dom elements based on this state the internal functions I collapse them so that we can see the component as a whole at the top we have the we import react and component because this file is going to be a react component we create our component as a class that extends the base react component we can do that now inside our class inside our react component we have three function functions the constructor a function called toggle showing and the render function and then we will look at all three of those in a moment but all the way at the bottom we have our export statement to export the component so this is one thing that's Python and JavaScript are a little bit different on in Python every named object is exported automatically in JavaScript you have to explicitly export the things that you want to export to be able to import them somewhere else so let's go back and look at those three internal front functions the constructor looks like this it sets the properties and the initial state of your component we haven't talked about properties and we probably won't get a chance to talk about them but they're essentially immutable parameters that that come from other components you cannot change them in the context of the component that you're looking at in this case there are no properties but there is some state there's state made up of a single boolean saying whether or not the Dib is show toggle showing is a function that when called toggles the is showing value the state from true to false or from false to true we use this set state to do that it's how you manage internal state inside a react component and then finally the render function is exactly what you'd expect it to be it's what it's what gets rendered in this case one of two things can be rendered and it all depends on the value of this dot state that is showing what's rendered is JSX it's very similar to HTML but you can use variables inside JSX the same way that you can use variables inside Django templates and yeah I just want to talk for a second about the on-click property that we put on each one of those buttons it calls that toggle showing function that we defined that switches the internal state and since the component states change the component is then re-rendered based on the new state if you've ever heard the expression data down actions up or one-way data-binding or one directional data binding this is what people are talking about when you hit the click button that action the on click event travels up the component it changes the component state and then that new state causes the render function to be recalled based on that new state and that data flows down the actions go up and the data goes down back to the log might not seem like this pattern is any easier and it's definitely a more complicated pattern for simple sites in this example this very little state where react shines is in examples where there is a lot of state to manage and when different components are affected by the same state so that brings us to the components themselves react if you haven't picked up on this already is component based you build encapsulated components that each manage their own state and then you compose them to make complicated you is since the component logic is written in JavaScript instead of templates you can easily pass rich data through your app and keep state totally unrelated to your Dom so we just built a single component the way to build a complex react to UI is to assemble these single components together like Legos you react that shouldn't be a monolith it should be a collection of components that each ideally does a single thing or renders a single part of your UI so let's look at an example where you have a single page app that has two views a landing page and a pricing page we want to build this as a single page app so the top of our component is so the top component in our tree is going to be the same in both cases I think I called it in X having the same parent all the way at the top that's what makes it a single page ad there's a plug-in called react router that I'm not going to have time to cover it handles URL routing inside a react app but I just wanted to let you know it exists and then the index component is going to render one of two possible components based on the properties it gets from react router it's going to either render landing or pricing landing is a component that renders your landing page pricing as a component that renders your pricing page each of those pages might be made up by other components might be made up by a whole tree of other components but the render page of your index method is going to look something like this where our top component index is not rendering HTML is rendering other components based on the properties that it gets from the router so render can render one of two things it can actually render Dom or it can render other components that eventually further down the tree render done and when the path name from your router changes what's rendered changes without a page reload so your application is built like a giant tree where the current view is made up of all of the components being all the way down to the base of the tree and when your application state changes all the components below it that are being rendered are going to internally check whether they need to change too and if they do they'll rerender it sounds like that would be super inefficient the way that it works is actually very efficient I'm not going to get into that but it's really fast and performant there's way more to say about react but I want to bring it back and show you how to integrate and react with the Django project because that's what this talk is about so lightning round this is how you get started using Django and react together the first thing is that you need a node for it you notice what's going to manage all of your JavaScript packages and including react so you want to install node and NPM which is the known package manager and then you want to initialize NPM inside your Django project and this is going to create a file called package JSON and package JSON is similar in terms of what it does to requirements txt for pay you want to install the node packages that you need and the way to do this is NPM install package name and then have a little flag at the end to define whether you want that package installed globally whether you want that package installed for the dev dependencies for development only or from development and production so here is what selection from my package JSON from one of my projects just a couple of things these are all the dependencies for this project that's needed for prod and also for dev a couple of things to focus in on all of the stuff that starts with bable bable is a shim for lack of a better word that takes your es 2016 or 2015 your es6 javascript and reduces it down to JavaScript that older Brad can read radium is a package that you probably won't use in a typical reactor project I like it a lot in class I have a vendetta against CSS and one of the things that react lets you do is eliminate all CSS rhenium helps you do it by letting you do media queries with and react without using CSS webpack stuff all the stuff that starts with web pack web pack is a module builder it builds the bundle for your app that your Django template is going to read from and build the app from um both for prod and for dev it's probably for you going to eliminate the need for tools like grunt and gulp and it also gives you hot reloading so just like when you change a Python file your server restarts when you change in JavaScript file your known server will be able to restart if you use webpack it's not the only way to do it it's just kind of the preferred way to do it I guess or a preferred way to do it and then finally something that I am probably not going to get a chance to talk about is redux which is something you should learn and make use of it's a package it's also a pattern for managing and updating application state that lets all of the state updates happen in the same place so you can simplify state management even further and also put in dev tools there so it's easier to see what's going on so yeah the next step is learn redux it's a hundred percent worth the time it takes to learn there's a really good video course by the creator of redux that I linked to here I'll publish these slides afterwards by the way but you should definitely check that out a few if you care to learn react then the next step is you make a server j/s file this is the file that you use to run your known server in your dev environment it's kind of like manage py run a server you would do no dot server or known space server j/s to start your known server it's mine looks like this and it basically just tells your web app your web pack development server how to run and it makes use of a configuration file where you store all your web pack configurations making that configuration file is the next step the config file I couldn't fit the whole thing on here let me see if I can actually can you see that or no on you see it now no all right um this is it just to it so I'm gonna have to describe this without showing it unfortunately and now I've made it so that I can't see it yeah but in your web pack config it gives you the ability to use different loaders to use different modules to use different inputs and outputs the inputs they're called entries and the outputs which is just called output is the part that you're going to be most concerned about what the output does is it tells webpack where to put that big old bundle that it creates so that javascript knows where to list of that Django knows where to look for it and then entry defines what the top component in your component your react component tree is so if you want to slowly integrate react into an existing Django project you might have multiple entries a small react app inside Django to manage a small thing that can grow over time but you can have multiple entry points multiple react trees I guess you would call them and you would define them in your web pack config I only have one and I call it main there we go I can see my notes again but yeah this is just to that in there there's also your index JSX file which is your top most react file which I included it just to and then two more components that that index JSX uses a fruit which is where your apps roots are defined and apt JSX which is the uppermost component that render that has the potential to render Dom and not just render other components it'll render other components too but it can also render now like a loading Dom and then finally here's how you hook the two of them together you install Django whim pack loader which is a nice little package that lets you call your web pack bundle so all of that react code and the other JavaScript packages that you're using lets you pull that from inside a django template and you add web pack loader to your installed apps and if you have multiple entry points you'll want to do some additional configuration that's really well documented on web pack loaders github and then finally the last step is inside a django template you load render bundle from your from web pack loader at the top of the page and then inside the HTML of the page we render the bundle that we're trying to render we called it main in web pack config so just as render bundle main and that's it that is basically how to integrate it into a project so I have more stuff that I can cover and I'm prepared to cover but I figured now would be a decent time to stop for like two or three minutes of questions in case anyone wants to jump in because I know that it might be green territory we use the same code base as owns a Mason but I would like to know what is the reality of that because I'm glad to say exactly the same but I don't think if you haven't your component your logic right and then your render short you're actually rendering different things right and you in a web application you have different components as well so that what is the reality of that yeah I mean I haven't worked too much with it but I know several people that have the kind of you're talking about with react native right yeah so react the first of all iOS react native is more mature than Android react native right now some most of the problems that people are having seem to be coming from Android react native it's good for certain types of applications applications that like render template views it's bad for applications that are super animation heavy and have a lot of like interstitial animations is also what I've heard in terms of structuring that project react lets you do it one of two different ways inside a component you can render different code based on the based on whether it is a web app or an iOS app or an Android app another thing that you can do is you can have different components to define what your app is so you can have index component JSX next to index component is JSX and you will just import that as index component and react is smart enough to know that if you're building an iOS app it wants to use the one that's iOS and if you're building if it's a web app that wants to use the one that's JSX does that answer it at all okay yeah I mean I think that the benefit is if you want your mobile app to do totally different things then your web app you probably wouldn't but if you want your mobile app if it's really just a distribution game where you want your Android app and your iOS app to be very similar to one another then being able to share the same codebase I think makes a heck of a lot of sense so I have two quick questions you mentioned Django rest framework and react yeah what's the workflow look like for logging for example and sending back and CSRF token and am I simply just grabbing that token on a JavaScript JavaScript ID from the cookie and appending it to a request or what's the react way of doing that yeah I'll show you some code afterwards or if you're around for the next couple of days basically the way that I do it is I have Ajax calls inside my Redux workflow where I make a from the perspective of a component it I just have a call that says get artists or something like that and inside that get artists function that I'll define it's going to check what artists I already have in my Redux store redux is kind of like the back end of your front-end and I'm getting deeper than I who wanted to on this but it'll check if I need to make a fetch first of all it'll check if I need to make an AJAX call if I do it'll make that Ajax call and get the response and then load it into my browser's local store ok Club yeah I appreciate that that probably doesn't fully answer your question no no that's and my next question is react can get really complicated as you know you can have models and a lot of business logic on the front end you can do the same thing on the back end in your experience how do you handle where that logic should land as far as Django models or models and react but where do we draw that line sure react doesn't have models that has modules so you're like importing modules from it's not like Django models so much I guess your react data stores could be similar to modules but um those would be populated by your uh your Django models um so what I would typically do is I would get the data from Django put it into react so I don't have to get it again if I need it again and sort of use it the same way that you would kind of use like SQLite if you were building an iOS app where you have like a local data store just for that user just for that session and then everything else just lives in Django and you have a workflow where you check if you need it if you do you grab it from Django if you already have it then you don't thanks yeah of course hadar a lovely talk I've really been appreciating a lot of the conversation I've heard around Django and react together my question for you is about style management and CSS David you don't like CSS and they're using radium for media queries sure are you using any of the libraries Khan Academy has one at the name of it to manage inline styles in virtual Dom elements no I'm not using those basically my CSS is so I've put a kind of rigid separation between components that render pages are only made up of other dumb components that don't manage any internal state so I have a component from button and I have a component for div and things like that and I define what those should look like by passing props to them and then all of the radium calls are done internally and I really actually only use radium for the hover and focus media queries things like that for things like with I do that declaratively by having a reducer that manages the window width so I can access that and declarative fashion does that answer your question yeah it does a bit um how do you reuse any style share based on unit 14 components sure um you just have it inherit from a parent like if you're using the same button everywhere you you really don't have to you're importing the button into your component so it's not like your button almost becomes a composite of the Dom element and also the style in the same way that it would be if you had a button that you put like I don't know button the success on if you're using bootstrap right thank you sure my question is about a little bit of architecture or maybe deciding when you are where you should migrate your application to something like react like for example the the button example that you made is traveling in jQuery right yep but how do you know when hey I could really use something that manages my state instead of just adding classes to my stuff and checking with jQuery but you know installing react is not like oh one comment thing I really have to commit to it it's probably going to change your build and a bunch of stuff yeah so when do you know hey we should really be using something more robust than just jQuery you know I mean I would say if you're starting a new project then you already know react it makes a lot of sense because it's no harder to do it that way if you're starting from scratch if you have an existing project that isn't using react I mean you'll know when you're spending a lot of time debugging jQuery because managing state is an issue so like how you do that exact calculus of whether or not the investment is worth it really has a lot to do with how much of a headache it is to fix problems that that happened when your state and your da more like intermixed so a thanks for the talk I have heard a lot of different opinions about combining like front-end and back-end especially in our Django projects and I'm wondering how you handle packaging up your your project for deployment since a lot of people have opinions about separating front-end and back-end bundles and whatnot like or a lot of people that I work with are really against having PIP you know be dependent on NPM and I tend to agree with them but I wanted to see what you thought about that um yeah I mean I tend to agree with that as well like Python Django has to run on the server its back-end react can either be deployed on the server or on the client it's front-end I like to keep them separate yeah thanks is that does that answer your question thanks for the talk this really demystifies react and makes it clear this is a state-based view technology yep so the previous call a previous questioner somewhat got into the issue that I wanted to know about which is when you're in development you mentioned running node both as sort of compass like watcher and also as a server for development to serve up some resources okay Django is going to call for in production and deployment I gather that you don't do that and I just wanted to verify that that's true that's exactly right yeah okay thank you so cool we have five minutes left there's any more questions if not I'll jump into some stuff that I wanted to cover but didn't have time to awesome so stuff I wish I had time to cover this is also a really good like I don't know study guide for what to do next if you're going to start doing any react development the first thing is the component life cycle so inside every react component there are seven things that can potentially change the props or the state of that react component it's only seven but knowing what they are knowing when they're cold in terms of when a component gets instantiated when a component gets released they call it mounted and unmounted can be really helpful I have a slide in this deck that you can look at that like does a brief description of what each one of them is the next thing is flux and Redux so flux was the little history react came out some people found that managing state in between components in react was sometimes challenging someone solved it with a pattern called flux that let a state be stored in one place relative to a component and then other components lower down the tree would access that state indirectly they would access that state as property so they couldn't edit it directly but then they could pass actions back to a flux store that would then cause it all to update the problem with that is you would have a whole bunch of different flux stores at different levels of your app Redux which is kind of a flux like architecture that everyone's moving towards it is Fluxx except it says all of your state transformations all of your state transitions should happen in exactly the same place in a Redux store reducer and what that lets you do is you have your application state all in exactly one place as a giant JSON tree basically and your application renders from that and if you want to change anything in your application if you have a button click or whatever you don't do it internally in the component you dispatch an action to your Redux store and what Redux does is it preserves your last state but also creates a new state for your app to transition into what it lets you do is debug things a lot more easily because you have what your state was and what your state now is so anytime you can hook it so that anytime an error gets thrown for a user that it sends their entire state history to a server so that you can debug more easily it lets you see what your react to what your application state is all at one time all in one place it's super useful to learn react router and Redux router those are the two routers that people use for URL routing inside of a react app they do essentially the same thing react router is simple and perfect for most apps Redux router add some more functionality that react router doesn't have it's probably too Company it's not too complicated it's probably over engineering for most apps but if you need it it's great and then yeah I will put some gists for authentication and access restriction using Django because that's something that I kind of scratched my head on for a while and that too the slide before I publish it basically you wrap your components inside an authentication wrapper that checks whether or not a user is logged in prior to rendering the component and then yeah cool I'll guess along with this learning react isn't hard because it's hard it's hard because it includes a heck of a lot of patterns but you're probably not already familiar with if you haven't used it before there are a bunch of little things to learn that are each easy on their own but altogether it makes learning react feel overwhelming at the beginning or at least it did for me but once you know react it can make state management inside a complicated app much much easier it plays really nice with Jenga because it doesn't try to do this stuff that Django already does well it tries to do one thing manage your templates and it does a really really good job at that so ah like I said feel free to reach out to me I'm on Twitter I'm on github and I'll be here for the next couple days for the for the sprints thank you all so much for your time
Info
Channel: DjangoCon US
Views: 19,467
Rating: undefined out of 5
Keywords: python, djangocon us, djangocon, django, react, JavaScript library, jQuery
Id: zYHv6U86X0Y
Channel Id: undefined
Length: 43min 18sec (2598 seconds)
Published: Wed Aug 10 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.