 Couple things about me real quick. I have to apologize my my voice is a little off my thinking is a little off I I either am allergic to Bangalore or I got a cold the second I arrived that feels a lot like being Allergic to Bangalore, so I've I've been trying to recover from that for the last couple days So bear with me So second I'm it mentioned something important Which is so I'm a I'm a proud full-time JavaScript hacker. That's all I've done for pretty much the last four years And the one piece of context that I I think is Important just to understand where I'm coming from and I think a lot of us are coming from someplace similar is I do a lot of work with Angular We've been using angular Very heavily at MDL since since it was released since 1.0 In particular because it's great for rapid prototyping you can get a lot done very very quickly So the world is moving on. I don't think people are moving away from Angular But we've got all kinds of new stuff and so my Investigations with with react and starting to deploy it over the last few months come from that perspective I'm still sort of transitioning and I think a lot of other people are so I hope that I hope that that's useful I hope I can translate a little bit All right, and then the other thing I have to apologize for a little bit is that I have the slot right after lunch Nobody wants the slot right after lunch Everybody's energy levels are up for like the first ten minutes because they've got a blood sugar rush going on and then it crashes, right so We're going to we're going to try to keep try to keep the energy level up I'll try to I'll try to not go crazy too often But but if I am if I do see anybody totally nodding off in the back I'm gonna let rip with I've been hanging out with Salman Khan way too much He just keeps saying that over and over and over and over But so if I see somebody nodding off because of the post-lunch coma, I'm gonna hit you with that Alright the Let's do a quick survey How many folks in here spend most of their time writing JavaScript? Cool. How many folks what we'd call single-page applications were mobile applications built principally out of JavaScript Okay How many folks have used react in production as yet, okay, you guys can leave This is we're gonna be starting from scratch so everybody else is in good shape Those the rest of you guys I hope that I hope that there's something I hope that there's some valuable perspective here But I just want to set everybody's expectations that we are we are gonna start With the most basic react component work our way up from there And by the end have a full, you know, flux pattern application going and we're gonna focus along the way on on some big ideas the the premise for me coming from having spent so long with angular and a little bit of ember and now moving towards react and seeing where Angulars going And Orillia and everything else that's happening. It seems like almost another paradigm shift already And so react in particular in bodies is kind of all in one place in its really fundamental approach A lot of the new big ideas that are coming down the road at us So just a few years after we sort of all began shifting towards single-page applications and JavaScript applications We're already looking at at some fairly fundamental shifts in how we do that. So the plan is Little bit of intro lot of code. I hope that I hope that works for everybody So we'll do we'll do an intro to concepts then we'll do demos with just react just looking at react by itself Then follow up with like some summary about that and then because this thing is two and a half hours I think we're gonna take a break in the middle little leg stretch Then same thing again, but with flux So a few slides just to set the scene and then we get to code so And again the so these repos so we're not live coding this thing That that just wouldn't work and in fact my demo wound up being probably 50% more complex than it needed to be But you can step-by-step Through the repo commit by commit and follow along with what we're doing If you really want to you can do that here today in the audience We just won't be able to sort of stop and problem-solve with you But even better, hopefully it's a it's a it's a takeaway It's something that you can take home and get some value out of even after the session is over and Then just questions. I'll be very happy to take questions The only thing I think all conference Attendees and hosts can agree on is that the best kind of questions are ones that are really trying to clarify something That just hasn't been said. Well, that hasn't been detailed enough and not what I call jeopardy questions Do you guys have the game show jeopardy here? Do you know that so okay? So the basic premise is that you get the you get an answer to a question and then So who says I was cooked to funny Cartier and on TV and then instead of saying Salman Khan You're supposed to say who is Salman Khan? That's the that's the catch of jeopardy So a jeopardy question is a question that isn't really a question You already know the answer, but you're phrasing it like a question And so instead of saying that's a really dumb idea You say well, don't you think in the context of a really a nangular and all these other things? That's a really dumb idea You already know where you're going with that And so just you can read a blog post about that and the reason is the only reason I say it is because it takes time from the audience So definitely hit me with anything that's unclear. Please ask questions and Otherwise we can talk offline afterwards So why are we here? What is this? Is this this looks a lot like the Chinese stock market? over the last nine months or so But in fact, it is the this is the the Google trends. Everybody starts with these But it doesn't prove anything the fact that people on Google are really interested in react now It doesn't prove anything about how good it is or whether it's better than anything else It does prove that it's got staying power, right? It came out back in 2013 and we're all like, oh It's kind of a clever thing people are talking that's Facebook. That's interesting and I myself I for a while wrote it off as React only makes sense when you have 200 developers working on the same code base. That's a that's a great way to solve that problem but It has it has born the test of time and people just keep adopting it and adopting it and adopting it Incidentally it looks like another adoption curve Which is Angulars which is not to say Angular is the bomb although it certainly does seem to be the big framework particularly in this region But it has staying power So this was the same period of time basically in the in the development of angular in this near parabolic interest curve I think indicates that react is is here to stay It's gonna be around for for a while And also it's backed by this little internet startup you might have heard of and They they seem to have. Oh, hello JS channel Let's cancel that They they seem to have something to do with the interest level and in react as well All right, so here's what we're looking out for today components components components components components The whole world I think is moving more and more towards The idea that anything in an interface should be Componentized it should stand alone to the greatest extent possible So the traditional MVP pattern doesn't really do this you've got all kinds of concerns all mingled together and one controller and one view Everybody's going this way angular two is going this way angular one already had directives angular two is making it explicit Ember has had the ember component pattern from from day one. I think And that's what react in particularly the library react is is all about view components And we want them to be dumb. We want them to be To really just know what they have to do show something take some input on that That's it get the logic for everything else that you're doing out of there and Decouple it decouple not only the components from the system, but when we look at the flux pattern later It's all about decoupling the different parts of the system from each other What the fancy term location transparent messaging that basically just means actions and events that where you have as few Assumptions as possible. So for instance the angular dispatcher pattern The premise is that you just everybody gets every event You're either listening or you're not listening and what that means is that nobody involved knows anything About what's happening at the other end of the pipe and that's that's a really powerful pattern The the world of react it's not it's not kind of baked in it's not a mandatory part of it But the world of react and the world of node seem quite close The more reading you do the more looking at examples both at Facebook and elsewhere You see that these patterns seem Seem to have merged and there are tools for doing things other ways that don't involve node you can still do lots of react with Bauer but This this is this is a trend and I think we'll see it I think we'll see node leaking into the browser more and more and more and I think that's that's worth checking out a Lot of node is about the Unix philosophy about small Sometimes even just single line little pieces of code and that that philosophy of node that philosophy of Unix Informs what we're trying to do with our components. It informs what we're trying to do with with flux and with where ideally our our craft is going in the future And of course since we're doing node a lot of the time you see lots of modules Explicit dependency injection again. You don't have to use those but I I think it's a best practice We're also moving towards everything in JavaScript. This is an interesting trend You'll see within 10 seconds with react. You're like, where's the templates? Where's the HTML? It's not there really anymore And so people have been taking the logical next step and actually even beginning to move all of their CSS into JavaScript again, there's nothing Necessary about that, but it seems to be the direction that that's that we're moving Virtual DOM is the big buzzword It's it's it's in all the in all the market speak But it's really about something else virtual DOM is really something that's hidden from you You don't really interact with it. You don't do anything with it What we hear is that it it makes our applications faster that they render faster What what's really important about that the the existence of that virtual DOM? Allows us to create our whole application structure without needing a DOM, right? So your app lives entirely independent of what's happening in the actual browser or in the DOM context specifically and Doing that makes it easier for us to get to to model things the way we want them to to move our data through JavaScript in a one-way flow and to move our rendering in a one-way flow You only go in one direction you render stuff down the tree then when you need to replace it You just replace it. You don't update it and then there's this interesting This is from a talk a paper that angular published as part of the angular two investigations They called it being DOM versus rendering DOM and we're gonna see this in our examples The question is do you start with the DOM? Okay, so do you start with a? HTML template on which you declared some angular directives or something like that and then use those as anchors to go out and grab some JavaScript and attach that JavaScript to something that's already in the DOM or Do you start with an application that exists entirely in JavaScript and use that to render the DOM? These are very different approaches now Arguably it doesn't necessarily on a given day change your life Whether you're using tools that emphasize the DOM to JavaScript model or the JavaScript to DOM model It's the kind of thing that starts being clear over the long term once you realize That all these dependencies are going away that all of these wait did I remember to update that too? Did my angular watches fire so that when I up when I updated that data some place else? It actually got noticed by angular so that the view updated as well Keeping everything in JavaScript land and then migrating from there to the DOM makes these relationships a lot a lot clearer and then the other thing that we're doing differently is is instead of You know dollar watch which is an angular construct or even we're moving towards observables but the question is do you watch things and then fire updates on that basis so keep the DOM where it is and Just go find this piece and change it and go find this piece and change it and go find this piece and change it Or do you just to re-render it? Do you just re-render the whole thing? And I just threw this in this is a great sindre soar who's has written something like five or six hundred node modules and This was just a little post he did recently But it basically just talks about that Unix philosophy and why the Unix philosophy Is is relevant to us is relevant in the browser is is relevant everywhere? So yeah, just go just go look at that But I'm sorry Sindre SINDRE Soar who's SOR HUS? and If you need the if if you can't find it, it's kind of buried actually if you can't find it hit me up later So what is react react is a library not a framework It really it just doesn't have the characteristics of a framework it it's just for rendering That's it. So if you start from MVC react is just the V. It's the view layer. That's it I Think that MVP. We're kind of moving on MVC. We're moving on from MVC the So react just makes components and then it composes those components together Into larger and larger and larger interfaces, but really Most of the time and most models that you see there's one master component that runs everything And you're gonna see in a second how bear that that leaves your HTML file It's not a tiny library, but it has a rather small API. It only does a couple things It's it's not for building whole apps and Because of that because they're they're trying to reduce their surface area and just do things that are critical We do basic JavaScript in most things. You'll find yourself saying well, how do I do x in react? How do you do it in JavaScript? That's probably how you do it in react? The browser support situation is good a react just relies heavily on the ES 5 JavaScript features, but if you just shim those you're in good shape The so your whole interface is a tree And as we talked about before when the question is is it Dom to JavaScript or JavaScript to Dom Are you saying that the Dom tree mirrors the JavaScript tree or vice versa? and in the case of react the Dom tree is it is a mirror of is downstream of The tree that react uses to model your whole application. So for every Dom element, there's actually a component This idea that it's only JavaScript We're gonna see that in the examples that we do here today It's not there are people who are creating tools for sort of importing HTML templates into react It does seem to be out of the mainstream at this point in time. That doesn't mean it's bad That doesn't mean don't do it If it helps you get work done, then it's a good thing, but it doesn't seem to be where where we're going and So data flows in one direction down the tree rendering flows in one direction down the tree And so we this word unidirectional unidirectional it comes up over and over again And so we never update the Dom we never mutate the Dom We simply re-render it and so eventually somebody who knows react already knows that well actually in the background react does Sometimes do things that you could describe more as mutating rather than chopping off the whole Dom fragment and sticking in a new one But that's abstracted from you. It's hidden from you as far as you're concerned What you get to think about is I don't have to figure out how to go back and update all these things I'm just gonna start over everything that I did before forget about that I'm just gonna do it again only this time different So let's see one code and so we're gonna be using this is source tree up wait. We need to mirror This is source tree. I'm a big fan of it for managing your get repositories So very simple what do we have here, let's make the this even smaller because this screen is really compact and I don't think I can even change the Resolution of that other one wait, let's try. Yes much better. Okay We're starting with the the simplest possible example. There's no automation here There's nothing else going on in this repository. We have a single HTML file We've got a redox library and we've got the JSX transformer library JSX is this syntax that we use to Create but to model our components in React and we're gonna talk more about that in a bit, but for now the thing to know is just that you have to Transpile you have to convert JSX to JavaScript before you can use it. What we're doing here is we're doing that in the browser Most of the time you want to do that before you deploy But and we'll see an example of that and then all we've got our whole body has a single div in it Which is just an example now that may seem like oh, well, that's just for the demo, right? That's that's crazy But that's actually how Not all but many most react applications work is that the only thing you've got in your index that HTML is Just one element and the whole react infrastructure hangs off of that that one element and Then This is where the magic happens Right now. We're simply just calling the react Render method and we're telling react to create a new element called an h1 Okay, so react knows what all the default HTML elements are even though our goal long term is to create these custom components with react react also knows how to build basic DOM elements and then we're going to populate it with some text and Actually, am I all the way back? Yep And then we're going to attach it so right here after the comma We're telling it which element to grab it with right so you could do that with jQuery. You could say Find this element and then attach something to it in this case We we try to skip jQuery when we can because react really doesn't need it And what that gets us whoops Get rid of that. We didn't play any intro music after all Whoops the If for those of you who follow along in the in the repo There are readme files and to-do files that clarify What we need at most points in time to actually run this repo in this case I think all we need is just a simple server. So we're just going to start HTTP stir Yeah, that's right. That won't work. So sorry guys localhost 33 33 there we go Hello world and so react is rendering into the DOM This this little code so it's just a tiny little thing and But that's the basics of what a react element looks like but that's a that's a toy example So let's move forward And the first thing we're going to do is actually we're going to get rid of the JSX transformer We really don't want to be transferring Transforming JSX in the browser. We want to do that with our automation tools How many of us are already using grunt gulp broccoli something like that in Development web pack anything like that most people it seems like it it it really is critical here because just to get from The code you're writing with react to what you can execute in the browser. You have to do this Transpillation step so you need something When you're working and so you'll want to adopt one of those workflows right now And all that is is the offline build simply happens We are installing this tool called react tools and then we're going to run react or the JSX tool to Compile our JavaScript for us and so now that that's running we have a server running That's really all it takes to to proceed on with this stuff And if we if we jump back. Yeah, we just changed the the s to a z hello worlds Very sexy very chic. All right next step. We want a real example That example that we did before we just went straight to make an h1 for me We didn't actually build a component before we asked React to render it in this case So we don't have any new to-dos this time So here is our hello world still and then here is this new component called the hello message Now hello message is a more traditional react component This is what you should do and the critical thing is we're doing react create class and Then what we supply to it the the The one critical thing that you can't have a react component without is the render method the render method simply says Alright, so we've got this object. Okay. I've got this tree of react objects. I Want to I want to do something with it. I want to put it in the DOM How do I do that the render method tells you how to put it in the DOM and so we're simply saying okay Give me a div put some text in it and then there's this thing here. This called props So react Passes data through the application. We're gonna look at the model for this more later But we have props and we have state. We're gonna say repeatedly and clarify more state is Mutable props are immutable right props are something that we're just gonna render it And then it's gonna stay the same until we re-render So in this case we know that we want to stick someone's name in and That name is down here Okay, so we created up here a component called hello message and then what you say down here to react render is I'm it looks like you're creating an element, right? This is an XML style syntax We're saying render the component called hello message and we do it in JSX by just putting it in there like that And then we're adding a prop. Okay, and it's just an attribute You know whatever we're used to doing with attributes in HTML or XML You do the same thing to create props and to hand data down and we're just saying put that on our container And so when we go back Now we've got two things now. We've got this one super simple element The h1 and then we've got a more traditional one the hello message which we've defined by name and then injected Now we're gonna do something more complex We're gonna switch back to this is the the traditional react tutorial And so our to-do here don't save Close close All right, so we have to kill that kill the JSX watcher Run the installer and then we just do node server.js which is really a much more sustainable approach to to development here so localhosts 3000 All right, and there's nothing there yet and what we've got the Yep, this is where we're gonna stay simple for now and we're gonna use reactify later Okay, and what we almost always start doing here is we start with We've got our index.html Okay, we have an ID called content and then we're importing our tutorial Our tutorial file is here. So we're gonna start you always start with something. It's often just called app Your your roots react component React or app main something like that in our case. We're gonna make a little tiny comment application So we we call it comment box and for now just so that we can see that it's working That it's compiling properly It just does that And that's it You know you start your react applications with your base element and and work out from there Next we add some more components So how do you do that? How do you nest one component within another? Well, it's pretty straightforward. This is JSX And this allows us to mingle Kind of the same way we would with Angular where we would define a directive that we wanted to use as an element And then just invoke it in our HTML We can mix together our fundamental HTML components elements like divs and h1s with Comet lists and comment form which are the things we just created And what we're saying ultimately when we start back out here, okay? We are Down at the bottom At the very base we're rendering react comment box Okay, then inside the definition of comment box. We have these children Or ones as the is kind of the the react jargon and those are defined here Those are just also react classes react components. Okay, so everything anything that has any significance in it You're gonna want to separate into a react component. You know here. We have Just an outer rapid div. We have an h1. Those don't do anything those don't have any logic They're purely presentational you can have a million of those all in one component But once you start doing anything like listing your comments or having a form for comments You want to break it down decompose it? And That's what we get The next thing we do is pass in some props So before where we where all we did was pass in just one person's name What we're saying here is that ideally whenever humanly possible our Components don't have to think about getting data. Okay, they're not in that business Only a few special react components have to worry about getting data the rest of them We just pass it to them as properties and So what we're doing so here so we start with our Comet box which has our comment list and then a comment form the comment list We've now fleshed out a little bit here We are we have sub? Components now called comments So in the comment box, there's a comment list in the comment list There are comments and what we're doing is passing in a prop here called author and then Another one. This is a sneaky one This we call that a child text node Right so whenever you have a P and then inside of that P you have some text technically that text is a child text Node and so we're doing that here and the reason I mentioned that is not to be pedantic although I run risk that sometimes It's because that's how react thinks about it React is going to take that text that's inside there and turn it into a sub node into a component and the reason that's significant here is Because inside Yes inside our Comments elements So first we're grabbing off of the properties this dot props dot author which we declared here and Then we're grabbing this stop props dot children. Okay, and that text that's inside is a child node This is a convention that you don't want to use real often It's probably easier to hand it in in another way But you want to understand it you want to understand that react is doing that and so the the bottom line is that that gets you The name and then the this is one comment This is one comment. Let's make that bigger So so far we're just composing we're today We're starting out big with our root level element getting smaller getting smaller and the other really critical thing We have to do is we have to get data in there now traditionally in an MV C pattern we would just have a controller right this big Modelithic thing that would have a bunch of elements an element for the outer box an element for the inner For the list itself and then elements for each of the comments But all the logic for all of them would be mingled together Which is great at first Until months and months and months later you want to make small changes and what you have to do to make a Small change to one thing is understand how the whole thing works You have to understand how the whole controller works where the controller is getting its data from In order to understand what's happening with this one component here this comment I Can know everything that I need to know about this comment about where its data comes from by just looking at this comment That's it. That's literally all I need to know. I know that somewhere when this element is invoked They're going to be handing me a prop called author That's it and then all I have to do is find the place in the comment list Where they hand me the prop called author now this component is entirely Self-contained you can change it replace it swap it in without having to understand anything more complex Then these very few lines of code and this of course is why an organization like Facebook loves it They have literally hundreds of people working on the same relatively small discreet Application you know to render something like a list of Facebook activity and They want each one of those hundreds of developers to be able to focus on one Discrete specific thing make the changes to that specific thing commit them and not have it affect anything else So if you're a if you're a solo developer The the the value of that doesn't pile up as quickly for you, but it does it does pile up over time Here's an example of how to add some Additional stuff how to use additional libraries. We want to do markdown. We want to take in template strings and turn them into Turn them into HTML now. We've already got that stuff in our Yes, we're calling this function called marked which is already linked in our JavaScript in our HTML here lib marked Only and we have invoked it because we've got some Where is our markdown stuff props that children to string Yeah, it's all in there Well, we have marked down in here somewhere darn it and It's not rendering and the reason that it's not rendering is something that again, we hopefully don't run into too often, but React is very concerned as Angular and other libraries and frameworks are about Safety of strings because you can inject other code in when a when a string is read. So what you have to do to get around that is Add this Hmm-hmm. It's in the comments It's all these comments here, which are now hard to read because they're so small We do dangerously set inner HTML. This is one of the very few things that comes, you know The few additional utilities that comes with react is this ability to say Yeah, I know I know that I know that template strings are risky But that's okay. Let me do it this time and once we do that Now things render now we have italics and we have peas and stuff like that Again, this goes to the question of whether we are trying to get rid of not trying to but rather the industry is moving Towards getting rid of templates as strings of HTML And moving instead towards all JavaScript Or if we're gonna keep doing what we're used to doing you can do what you're used to doing Just know that react is set up. It's gonna make you jump through some extra hoops to do it Marked is just it marked as a as a react. Sorry a markdown parser That's all it is. It's just a standalone markdown parser React doesn't have anything like that built in and you wouldn't want it to like it's a it's a separate concern We want to pipe that module into our app Yes, okay. I think the question is specifically that we're all used to separating our concerns, right? We keep our HTML in one file. We keep our JavaScript in another file. Also, we went through the whole phase of Unobtrusive JavaScript right that we should just be using jQuery to go find some element and then attach JavaScripts to it rather than sprinkling our JavaScript inside of it And so what is the philosophy? I think you were saying that we are getting away away from that Fundamentally, I don't think there's anything about this approach that says HTML is bad. HTML should go away But we're doing two critical things one We're starting from our virtual DOM from our representation of the entire application in JavaScript Since that is our starting point now instead of HTML to which we attach JavaScript That's kind of step one that's part of what makes us start thinking Oh, well, maybe we could keep everything else in JavaScript as well certainly for performance not needing to go find in Little HTML fragment and import it as a separate file each time over and over again You're definitely going to get better results out of that even with Angular actually when we send stuff to production or our other frameworks We often pre-compile all of our HTML into JavaScript right because it's much more efficient to just pull that straight in But the other reason the reason that we hypothetically don't need to have our templates over here and Our JavaScript over here and have them be separate concerns is because now These react components are so atomic. They're so small and so discreet You know the comment list even though this is a component that's going to have a whole bunch of other stuff rendered inside of it The whole thing fits into 10 lines of code We've got our template right what are our DOM elements going to be we've got our logic Although there's really no fancy logic here for it yet All together in one place in one file So we are still separating our concerns We're just not doing it the same way that we're used to now part of the reason that we would keep our HTML and our JavaScript separate the way we do is because it's easier to manage in some ways, but there was also an asymmetry Right you didn't have one JavaScript file for every piece of HTML or for each template in this case though There's just the component. There's one JavaScript one Template if you will one JSX one one set of elements that are going to be rendered and so it's a match It's a it's a direct one-to-one match. It's a storing them together in one file I think Seems seems to work I'm not tripping over things the way the way I might have expected to To import a template. Yeah, you're saying he's saying that it's certainly possible that you could import templates Have a layer of abstraction for that. It's absolutely possible. There are tools for it So it's it's absolutely doable. The one thing I would say is try this out first and see if After you've built a couple things with it and and seen it scale a little bit if you still feel the need to Maintain your templates separately. There are going to be circumstances where with certain things for instance markdown That's why markdown is in here as an example Let's say you're rendering a wiki right and you're going to grab a whole bunch of stuff and Inject it That's a great use of separate templates of separate data, right? But once things start getting atomic you don't really want to keep two lines of HTML in a separate file There's sort of no point Because and that's what react does to us. It really gets everything quite quite compact Yes, and in general so when we get to our flux example, we're going to do all that stuff You're going to see how it's generally modeled out and in react land people tend to do that with With browser fi and they import common JS modules and so each individual component will almost always be a common JS module No, they're all it's all in fact the basic premise is That almost nothing is in the global namespace There are other frameworks that do this as well But so for instance with an angular app that you manage with bower where you get your your subsidiary dependencies JQuery your charting library whatever else you have going on when you manage that with with bower Those are in the global namespace The model that you see most often with react is that each and every individual react component is Not in global namespace and neither are jQuery high charts, whatever else you have going on That's all part of basically whichever module loader pattern you're using But you'll see and it will see examples of that We won't go way into the how it works But you'll see I think in an example of how you Reveal a module how you expose it and then how you import it and make use of it And again people do this with the ES6 modules They do it with AMD and they do it with common JS, but common JS just seems to be seems to be the most common Real quick, so let's finish up our react examples here. We're going to just All we're doing we didn't change anything significant now. We've simply moved our data into a real data source Not just declaring it in line on our elements I think that's supposed to be Jordan Walker and What you can see is that? Let's just glance at this Comment list comment data. Yeah, so here's where we start to We actually are starting way down here on comment box This is where we see how data flows down the tree of react elements So starting with the comment box. We are adding the comment data To comment box the owner element the outer one And so we hand it in we've created this comment data up here at the top of the file Down at the bottom. We have our comment box. We're handing it in and that then goes so inside of comment box We have our comment list and then what we're doing is we're passing the data down to the comment list And we're saying hey this dot props dot comment data This belongs to you as well and then in the comment list We can reference this dot props dot comment data and actually do something with it now. What that means is that you? repeat the passing of data down from component to component This is a little bit of extra typing. This is this is a few more keystrokes Then if all of these components live together in one big controller and you could simply reference whatever you wanted Whatever and wherever you wanted it But again, it's it's all about the separation of concerns and about knowing that at each and every level of the tree Here's how data gets into this component. Here's how data gets back out of this component And there's really no questions. There's nothing you can't see in 10 or 15 lines of code The way that we're making use of this We're now rendering these two comments with kind of a collection view or an ng repeat And this is one of the most common Conventions that you're going to see. Oh, yeah, here's our comment list And Instead of having a react tool that allows you to you know, create a list of items We just use basic JavaScript. We're just using array dot map Built-in function in in JavaScript from I think he has five onwards and we're saying map on to the array of comments the creation of a new node for each one and Then so that's the comment nodes So we're mapping the comment data on to this creation function, which will create a comment Component for each one and then we're saying down here very simple We don't say ng repeat comment in comment nodes or something like that. We just say yeah, put the comment nodes here The reason you can do that is because comment nodes is itself just an array. It's just JavaScript It's a it's a JavaScript array containing JavaScript objects, which are react components and React knows okay when I get an array of react components. I'm just gonna I'm gonna render them I'm gonna spit them out And so this has other implications for things like sorting, right? You have this arcane nut arcane, but really the syntax gets very long when you're setting up an ng repeat You want to sort it right? We just sort in JavaScript. We do it right here inside the component Do it with our data first and then render it out All right. We're almost done with this The one thing we're doing on this example This is an important thing in general with our Fundamental components keep hopping around in this file. My apologies for that. We use this critical method called get initial state Get initial state in general when you start with your root level You don't hand in all the data just in JavaScript generally somewhere you have Components that are responsible for retrieving their own data from somewhere else in the application And you do that using this critical method called get initial state and so what we're saying is we're going to get the set up a comment array and Then use it to populate Everything else that's going on here And so we pass it down by putting it on the state of comment box. We can then pass it down into the comment list and When we begin updating it in the next example with live data What we now have is a dynamic process of retrieving data Okay, now we have more comments We're retrieving data from this JSON file I'm not going to spell it. Ah, it's cool to funny Carti. Hey, there we go What's that as an extra colon? Where do I have an extra colon? All right? I did. Yes. Thank you Rep put the yeah comma, thank you. See this is why we don't do live coding and There it is. It picks it right up because what we set up in the in the component Was a there's a timer here somewhere We're just we just have a timeout inside one of our components and that timeout this interval here Is periodically just running a function called this dot load comments from server? And What it is doing the critical thing is it's doing this dot set state Okay, set state is critical to understanding how these components work So we've got our comment box here. We did our get initial state and we populated it with an empty comment data array What this function down here is doing is it's it's setting that state It's now populating it with our data. So each time we've talked here about how React doesn't mutate the DOM. It doesn't update the DOM. It simply Replaces it and so whenever you do set state You're going to trigger a re render So this method here the render method is going to run all over again Okay, so now we have the full react lifecycle here We're setting up some components one of those components the top level one is reaching out getting some data Pulling in that data using it to set state set state immediately triggers a re render and now that data Flows down into the children who are all themselves Rerender because they're below the top level component on the tree and the interesting thing about this You'll see this very common this very frequently when we do our get initial state We're setting up an empty Array here there is nothing in it now this normally sets off problems of oh Gosh when I update that array later How am I going to ensure that it you know populates that it gets back down into my views? React takes care of that that all disappears that Asynchronicity between data updates and the view goes away Because a fresh component is going to be rendered using the fresh data And it's just going to go all the way down the tree until it runs out of components to re render and And I think let's see it's almost two already Yeah, we're gonna see more about this this individual react stuff going on later into the other demo So let's jump back into keynote for a second. So components Components are react class instances. They're not really object oriented though. This is something There's a very smart man. He's not sitting at his table anymore It's very smart man in attendance who some of you have heard of he remind us to go with the grain and Use functional patterns whenever possible at the moment react create class as a functional constructor not a pseudo classical constructor our components have these lifecycle methods We saw set state and render are kind of the most fundamental of them But then there are these others that we're gonna see later on so so that you can attach handlers for instance and those happen After the component has mounted We have props in state. That's our data. That's how we get our data down through the tree JSX is how we compose the view we're gonna learn more about that in a second and We can both on a react component We can both add our own methods and we can extend the existing ones react does something clever Where it has this fundamental thing called did component mount or no, I'm getting the name wrong But all of those internal life cycle methods If you add your own it's going to run both of them It's going to run both the super method and The additional one that you're adding and so you can actually add multiple versions of it And it's just going to run them all in a sequence so mix-ins are Because we're doing a lot of kind of slightly object-oriented stuff even though it's functional in nature We want to be able to reuse code. So mix-ins are reusable methods that we often use for kind of glue functions and The problem with that is it's a great idea You can just apply a mix-in to a given component or to a whole bunch of different components and get a lot of functionality right away without having to retype it each time The problem is that they're going away in ECMAScript 6 So if you go home today and you start reading the react docs You're going to see all these mentions of mix-ins and you're going to think oh, okay mix-ins. That's how I do react In the in the rather near future. Unfortunately, they're they're going to go away and Part they they also have flaws, which is that you have to sequence them properly and that's a leaky abstraction So higher order components. This is where we go back to functional patterns We use functions to compose new functions. We use a generator function that will take an existing react component augment it with some new methods and then spit out the the new augmented component as as the return and that's what we're going to see going forward so Mix-ins still useful right now, but when you move to ES6 In the not too distant future, we'll have to adapt So rules on props and state People always ask this wait I don't get the state and props thing days from now weeks from now. You're still going to be like what should be state What should be a props? I know that it's all data that it's all data passing down through my tree of react components and It's not about the kind of data some people will say well really Props are for stateful stuff, but state is for the really data stuff and you're like no no no It's really about where it lives where it came from and where it's going It is state in the place where you can modify it So in our case in the comment box, right? That was the outer element That's the only place where you can retrieve and update that data. That's where it is state Everyone downstream of that who is consuming it is receiving it as a property for them. It's immutable. It's unchangeable It's untouchable. That's the difference you'll see various versions of this of this distinction But that's what it boils down to And then the best practice is just don't retrieve the same data in multiple places in the in the same tree in the same hierarchy Otherwise things get wonky fast We say okay, everybody makes a big deal about one way data flow data only goes down It never comes back up changes only go down. They never come back up That's mostly true But sometimes when you've got a child down at the bottom of the tree that has a button or a form input or something like that You want to be able to do something with that data. You want to be able to send it somewhere So often we'll make that outer comment box Component the custodian of all state of all data changes and we do in a way Pass data back up to that element, but we do it with simply a callback We pass down a function to the child and so the child isn't really executing the logic that does it It's the owner element. It's that top level element that is doing it And that allows the owner element the top of the comment box instead of the individual comment to be the logical Clear maintainer of the state The only place where you can update data So GS JSX Everything in react is JavaScript doesn't have to be we can import html templates if you want But by default they're going for everything to be JavaScript. So JSX looks a little bit like html It is not html. It doesn't behave like html. It's simply a syntax that kind of resembles html And it's actually closer to XML or x html So JSX Bridges us it gets us something that's more visual That we like better it transpiles. This is what JSX compiles to it is kind of like the callback tree from hell on some Huge asynchronous callback callback callback callback everything gets nested So what we've got here is elements within elements within elements or Objects within objects within objects. Technically. These are function calls that return objects and we wind up nesting these in a way That's completely unreadable if you really want to You can write this yourself You can go straight to this this JavaScript But nobody really wants you to and even the react team Don't recommend it So this is is much more readable We're much clearer about the About the hierarchy about what wraps what you can see in green this div We close it at the end. We're used to that. We're used to html and it makes it a little bit easier when we When we jump into our browser and start debugging we can More easily match up what's going on in our JSX with what's going on in our html These are just specific things that that you'll learn but What's important here come think of your components as classes so name them JavaScript convention other languages convention a class name always starts with a capital letter Whereas the traditional html elements Technically inside react those are classes as well But for convention's sake and to make it clear what's custom and what's not you lowercase those We camel case our attributes you really want to avoid doing hyphenated or snake case attributes Again, that's because this is JavaScript. We're trying to use JavaScript conventions and also because this is getting transpiled So you have to stick very narrowly to the JSX syntax and you can see you can't even use the word class anymore because of Course class is a reserved JavaScript keyword So you have to use the word class name the attribute class name instead And we even have to wrap our comments So a standard traditional JavaScript comment we wrap in curly braces So that it can be interpolated as JavaScript and so remember everything even what looks like well That's just a div right. I'm actually kind of interacting with html No, no, no somewhere there is a predefined react class that will output html for a div, but they're not the same thing Even that div is is JavaScript So the life cycle We kind of tried to talk about in terms of our elements our comment box. Where does data go? From creation we set our state in our properties. The first thing we do is the render method then We have custom methods that will show on our later examples to attach our handlers and do anything else that does require Interacting directly with the newly created DOM Then we get user input the DOM events in the bottom right-hand corner And what we're gonna see with flux is that we take an event handler Okay to to receive that action somebody pushed a button what now and we're gonna dispatch an action Basically an event in the terms that most of us are used to we dispatch that event Things are gonna happen and what's gonna come back is that this element is now going to set state It's now going to do an update which triggers a re-render This is just a really detailed version of the names of each of those life cycle methods The most critical ones are the three on the left So you're gonna see these long lists of eight or ten life cycle methods focus on the three on the left Component did mount that's the same as in Javascript in traditional HTML and JavaScript. We have to wait for our DOM to actually be ready DOM ready Okay, component will mount is basically DOM ready Component did update is the same as DOM ready, but for only after a re-render so that we can distinguish between that initial render And all the subsequent ones that follow and then component will unmount is like an angular on the destroy We tear down all of our event handlers and other library objects and things like that Component will unmount does that for you in in react these others are advanced ones. We're gonna skip right through those So again In our DOM In our live application your user is interacting with components and The bottom line the fundamental thing that they're doing that is mutating the state of the application All of those things trigger calls to set state And so let's say you change one piece of data that is reflected in ten different places Well, each of these little red arrows is going to be a set state that's firing on each of those components making each of those components dirty in React terminology So everything below those everything below what's dirty. So the blue ones is going to be re-rendered by default So set state changes data They turn dirty they get re-rendered You can Hypothetically prevent that what you can see down in the bottom right. We've walled off Over here that part is getting re-rendered over here It's not and that's because you can use this method called should component update to sort of intercept What would normally update your application? this is a In optimization and it's not the kind of thing that you want to jump on right away It's the kind of thing where you want to get your application up and running Not mess around with should component update and then go for that optimization when you can prove that it adds value with your profiler and so the controller views So we had this we had this hierarchy of components There's one that you'll see this this name varies a lot Some people call it the controller view some people call it the view controller Some people call it the owner some people call it the stateful component because it's the one that owns the state Whatever it is it does mean that even though in react we say oh no all components are the same Everybody's just tiny atomic components. There are components that are more special than others and these controller views are the ones that sit at the top of a branch of the tree and Handle things like retrieving data and then updating all of the downstream elements So the goal is to have as few of these things as possible and keep most of our components Truly stateless just have them be as dumb as they could possibly be and even these controller views We don't want to overdo what data we put into them, but At the very least whatever we do need to put in them will be encapsulated Just a couple quick recipes with react So conditional content the equivalent of a of an ng if It's just JavaScript So in this example what you see down here Sorry, this text really isn't Let's blow it up as much as we can what you see down here in this line is an interpolation and What we're doing is we're just using the double ampersands and We're saying if this value is truthy then render JSX stuff if it's not don't That's it. It's as simple as that. You don't need any special API. You don't need any special tools It's just JavaScript and here's another way to do that you can do it with a tradition a ternary operator And you can say if the windows logged in show me the nav element if the is logged in Value is not set show me the login element instead and if And if it's more complex than a ternary can handle you can do it with a case statement You simply set a value content in this case up at the top You define whether content is the nav element the login element or the something else element. Sorry component And then at the bottom you simply say render whichever one of those I chose in my JavaScript But you don't mix the logic to make that happen Into components themselves into the react API. It's just JavaScript Similarly we already saw how to do a collection. We simply take we use a map We map a component onto an array and What we get back in this case items? We simply Interpolate with curly brackets down at the bottom items an array of react components. That's it It's just JavaScript. There's no there's no magic there. There's no special API And in fact, I think to a certain extent react has to do some work to Avoid imposing a new API on us, and I think they've done done nice a nice job with that And there's multiple formats for that so So react is very similar to other things you may know to ember components to angular directives But the it's the implementation that really varies The good thing is that there's as little magic as is really possible The magic is really just in the diffing algorithm and deciding how to render things the important thing is that what react is saying to you is 95 99% of the time let us worry about how and when to render things What you can do now is just think about this in terms of it'll just be Rerendered and that's it and you don't have to worry about Statefulness in the DOM you can focus on statefulness in JavaScript let react worry about statefulness in the DOM There is a bit more typing Then a little more boilerplate then with certain other tools certain other patterns particularly once we get into flux But the tools for your browsers for your sorry for your text editor for your IDE for sublime Eliminate the the vast majority of that And react ultimately is not a full application framework. We didn't see how to build a whole application with networking in Services and all kinds of other stuff like that all we saw was how to build Components just these little tiny interface widgets. So how do we how do we get that? So we already did our stretching In a couple of couple slides ahead of me We build our whole application with with something else with the rest of the pattern so The default what most people start with with react and I'd recommend definitely your first application or to try flux on for size Don't a couple people have asked me already about the other competitors for flux the third-party stuff It's all it's all good stuff I would just say that for the sake of knowing where you are and what the pros and cons are I Recommend starting with flux and then going on to reflux or redux or alt or or one of those others So flux is trying to improve on the MVC model Which even on a good day? You have a controller, but that controller is updating a million different models And then once you update that model There's a million view changes that cascade off of it and they overlap and they cross over and And it's a pain Flux is trying to fix that it's not a framework. It's not even software It's not even a library. It is really more of a pattern more of an architecture more of an idea that Facebook has really more specified than released They've sort of shared it with us. This is how we do it and they've given us a couple of the tools that they use But most of the tool most of the flux pattern is just basic JavaScript or in one case kind of a node component So yeah, most of it you create yourself or you bring your tools from other places Flux doesn't even include a router That's how lightweight it is, you know We wouldn't the ember and angular teams wouldn't dream of not shipping Their framework without a router. It's it's so fundamental almost everybody wants one But they're like, yeah, you can get you know other people make good routers. Why should we? So let that be a separate discreet concern and use basic JavaScript wherever possible again the further into flux you get the more crossover you see into the world of node and npm and You see it. It's evolving The the the alternate flux library that was hot Six months ago is all of a sudden no longer hot that guy deprecated his library and said go use this guy's library instead It's it's evolving really really quickly. I Think that was fluxer. I think fluxer has been duplicate or deprecated after after being big for some time Flux is basically just made up of these four basic ideas Actions dispatcher stores views the bomb one the views that's already our react components We don't have to learn anything new about what our views in flux The dispatcher is just a dumb pipe for connecting together the other guys So there's really not much you have to learn there The interesting thing is the stores and the actions So whereas before in a in a controller in an MVC controller Sorry, I have to keep the scratchy throat going In an MVC controller, you've got a lot of logic. You've got logic related to manipulating data All merged together in one place manipulating the view the stores take that part of the controller function and Separate them out. It's they're purely about storing and modifying and updating data and then really Truly glue that binds everything together that allows you to move logic or move a flow throughout the application is The actions the actions are where you say go do something that will have consequences throughout the application There's also some use of an event pattern but in general When when Facebook is is trying to be really simple about it. They say this is it. This is the whole thing Action dispatcher store view. It's a one-way data flow a straight line. It's perfectly easy Really it's a little more complicated than that But what you can see here big ones Action dispatcher store view are still intact. There's still the big concepts What the other pieces are Telling you is that there are things that from a programming point of view well technically There's an event that was dispatched to get from the store to the view and yes events are an important concept It's an important object to understand but That's just what gets you Through the same pattern through the action dispatcher store view cycle So, but this is a really useful. I like this particular diagram Better than the one before it for understanding What's what's really going on with the little extra pieces of JavaScript are that that bind this thing together? All right and back to code already. We're gonna make this thing It is probably more complex than we we should have tried to render today but everybody else every other demo you've ever seen anywhere has done to do's and chat applications absolutely to death And the advantage of this one for me is that it's something I had done a while back in Angular and I wanted to a reuse all the styling and stuff and be just I Had I had built react apps from scratch But I had not Taken something that I had previously done in Angular and torn it apart and rebuilt it in react just to see how it worked So let's let's do that. Let's get rid of that guy switch over here This is our JavaScript. There is our repository Okay We're going to start this is We were talking earlier about modules and stuff like that. I promised you more on that in just a second This is more that the whole traditional the whole shebang the way you see most React applications working. I like it. I think it works pretty well And but there's still a million opinions out there. You can do it the way it works for you We're using a little bit of gulp gulp is Still fairly well known by most folks web pack seems to be bigger than gulp and certainly grunt in the In the world of react, but it's by no means monolithic. It's not everywhere the critical thing we're doing here where before we were Transforming our JSX in the browser now. We're doing it with this library called reactify and So we just are setting up a watcher here and that watcher is going to grab all of our JavaScript find any JSX That's in the JavaScript Transform it and then put it where we want it to be Then the other thing that we're doing so let's actually Let's start with index.html Index.html even simpler than it was before we have exactly one script and that script is starting with main So before we said You know that that you have very little html in this case, you know because now we're compiling everything you have very little You have very little JavaScript either So everything starts from Sorry with index. It's easier to move from left right We invoke main and we send it to container So in main what we're doing here is using the common jf pattern from node We have specified our NPM dependencies here. We ran npm install to get browse find go react on a sign And now we're just requiring the ones we need and all we need for starters is there's a module called app Which contains a react component and we're requiring react itself and People look at this stuff and they go oh I have to type all of that I have to import every single thing I ever use and just a Once your constraints are really narrow. You don't have to do a lot of it Be the tools make this really easy. So all I have to do to re import react is is that it's You know three keystrokes with a with a file matcher and that's just an extension for some of my And so what are we doing here? So we're invoking our root element and we're attaching it to the to the tiny Minuscule a little DOM that we already have in place and we're simply saying render this basic app And that's what you're seeing here Whoops, but what I have to do is I have to Use the read me and I have to just Start Gulp there we go. So we're using gulp to reactify our JSX and then We're starting a very basic because we didn't merge it into our automation starting a very basic little node server called HTTPster and now There we go We made everything so large And I think it's three HTTPster is on 3333 Oh, I didn't CD to the correct directory. Sorry about that CD dist Yeah, there we go All right, and so that's it. That's our that's our back end gulp We've already heard about gulp. We use gulp to transpile our JSX and then we inject our first component Routing is something that we haven't seen done before React in general has a very interesting way of handling routing. It's very declarative We're an angular for instance, you go off into this other file somewhere and you declare a bunch of routes and the configurations of those routes Here we actually do it inside our root level component. We import these tools called Routes the react router component and then it's sub components locations and location and What we do then is say, alright, here's a bunch of locations for each location Here's the path that it corresponds to and then here's the handler and that handler is nothing more than a react component Component called login which goes on the login path component called ideas on the ideas path That's it This thing here called superstructure is nothing other than sort of the outer the chrome if you will of the page the header the footer stuff like that and What we're doing then is delegating this that props that children is Delegating to the stuff that's coming through from the routing And again this that props that children is a basic react concept. It's not API for the router. It's just stuff It's just JavaScript and so once we have that we now have a login route We have an ideas route and we can hop back and forth between them For what it's worth I'm using here a router called the react router component. It is slightly simpler I thought it would make a better demo, but the Seemingly undisputed hands-down champion that most people that seems to get most of the love is just called react router It is sort of the react equivalent of the angular UI router. All right, and we can start doing Whoops one of the things that you have to configure on your router is how to handle Bad routes we haven't done that. Okay, so here we go. We've actually got some stuff now To look at to interact with we actually have a form So the question is how have we implemented that form? So we look in our components. This is an important thing about react in general we organize everything You're asking before about separation of concerns often. We've got a folder for JavaScript a folder for HTML a folder for CSS In react land you almost always organize things by the component. And so if you did have Same as with the gulp Generator gulp angular workflow, you know, you have a component driven thing, but you have a lot more files in each component here You generally just have your JavaScript And in this case you can mingle Some concerns together so in the log in workflow We've got multiple things that are part of log in and so we can just put them in one folder Or we can put them in separate folders, but each one is a component each one of these is a Component that we're exporting see this line down here at the bottom Okay, this is how we make it basically into a common JS module and make it available to be imported Using the required pattern up here at the top So every component is is executed that way. Yes Yeah, there's there's kind of nothing special about that It's all that is something where you're going to be working with the API provided to you by your React router of choice It's all there. I'd recommend just checking out the react router Documentation and and the examples of how to use it Notably the other thing that I think goes to two questions people always want to know How do I do conditional routing for things like log in and how do I do async data loading so that I get data? So like with the angular route resolve, how do I get my data into my view before I render it? and React router has has a way of doing both of those things I'm sorry speak up. Oh, yes, exactly. That's what we're about to do So we're not doing any ideas yet. We're still working on the on the login page. So here's the login component um Basic HTML some divs and note that whatever you return From your render function needs to be just one element. So if you have a bunch of siblings, you have to wrap them That's just something you'll run into in the compiler So we have basic divs here, and then we have this thing called login tabs Login tabs allows us to show off the fact that we already have a bootstrap implementation for For react and it's really quite mature So we're taking advantage of the tab pane from Bootstrap and so that's that allows us to jump back and forth between these tabs and You import it just like you do anything else you import the component and then you make use of it here in in your render function and note these These props here event key Okay, we're just declaring those as attributes Inside of this tab pane event key is going to be this dot props dot event key And that I think is everything we've got here except that we also have the sign-up form element So this sign-up form this is where we're starting to see a more complex element part of the reason for this Sorry about this. I ran a pritifier on this Anybody who uses I I have a pritifier set up in my JavaScript so that rather than manually Re-indenting everything I just hit a key in it boom it does it all for me and takes care of the white space Your standard JavaScript pritifiers will mangle the heck out of your JSX because they don't recognize it And that's what happened here. I apologize for this So there's an add-on for sublime or it's actually I think just a setting for babble That I'll prevents that from happening But as you're as you're getting into react you'll need to make these you know tooling adjustments so that you can Not not experience pain from this But there's nothing terribly fancy about this form here. It's a standard form. We're using basic HTML form elements div h4p a regular plain old input What's happening though? Well, we've got our first event handlers In react you declare your event handlers in line on the HTML. This is kind of like how angular does Directives we mingle Mingle a little bit of JavaScript back into our HTML and it also makes sense It's not really a separation of concerns the way it used to be Because again the whole thing the whole component is encapsulated right here So when I declare this on submit handler, okay, and I say on submit on on the submit event that is a react specific event Fire this function this dot on form submit and boom there it is right there five lines away So everything is tightly bound is is is right together all in one place rather than having to go track three files From here. What's happening? The one other thing that's happening here that's going to be our submit and then on each of these inputs Okay, so we've got two inputs for the name and the email address. We have an on change handler Okay, so this is where traditionally in angular for instance. We would set up Two-way data data binding we would do ng model or something like that right and boom ng model It's taken care of Here we have three or four more lines of code to write than that What we're going to do is just on the change of each of these. We're just going to do set state Okay, that's what updates everything for our whole component hierarchy with The value that's coming from the target element That's it that that gets us our binding of the value in that input to our Presentation of the state of the data for our component and I think that's it for This phase login tabs login tabs sign up form. Yep, so let's do something useful with that This is where we get to our actions This is where we really start to break out of the world of Just react and we start moving through the data flow around the whole application The first thing that we're going to do Yes on the forum in on submit. Yep. I have what? Yes, an action and we're about to see the action with the action. Yeah, we're about to see the action. You're preempting So the the we just set up our field that the great thing about this actually is that we can move step by step We can figure out how to obtain our data put it on to the state do that first and then move through the whole the cycle of flux So what we're going to do now sometimes it's quicker just to jump Jump in here We're going to we're going to create our actions So those are here in their own folder. Here's a file called Actions and we've created an action called sign up new user And what you should find in the sign up form is that on submits And now we have more methods here on form submit. We're calling actions dot sign up new user and Again, we're injecting everything using common JS modules. So we declare Var actions equals the module that stores our actions and then we can reference the methods that are exposed by that module so in the In that cycle we looked at they drew a distinction between something called an action and something called an action creator So to the extent that there is a distinction the whole thing we think of together as you know actions by the action creator what they mean is a function That creates an action object and does whatever else needs to happen So in this case What we're doing is we're calling our API. We've created an additional module called API utilities and In this we're just emulating. We're mocking a server call And so in this action, we're saying all right My user wants to register himself. He's provided me with an email and a password Please go to the server and check and find out if this is valid if so register him and let me know what the response is and That returns a promise validate new user Returns a promise So promise dot then and this is where we actually dispatch The the action depends on who you ask but this little object here Technically a lot of folks refer to seemingly as the action object and that's why this function is the action creator To the extent that there's a there's a difference there So we've started with the view the view has triggered an action the action is now invoking the dispatcher the dispatcher is This guy here very simple very basic code the Dispatcher this dispatcher is a library that Facebook released It's the only part of the flux pattern that is actually code. That's actually a library so we just create a new dispatcher object and We Let's see here Basically whenever the dispatcher is is a dumb pipe whatever we pipe into it It's going to push back out to whoever's listening and So in this case, we're going to dispatch a view action and we're gonna pass along this payload here this type and these credentials and And so anyone who is listening Can can receive the response so I don't know if we did that yet in this commit I don't think we have so what we've done is we've created the action we've sent it to the dispatcher and What we can do in the next step we want to do something with that right we want to Tell the app parts of the application that something has happened That need to know and then close the loop bring it back to what happens after the dispatcher receives this view action It sends it to the store Whoops misspelling in this case, we're using the user store store is ideally we divide up based on Your entity types or perhaps a domain of the application if you don't have something that's that clear and object oriented as an entity type But you'll have several of them and they should separate your concerns your users should be in one of them your ideas should be in another and The In the store we're registering with the dispatcher. Okay, we started in our view. We created an action We use the dispatcher to relay that action to anyone who wants to hear about it and what we do is we We hear we receive all of the actions that come in and then we do a switch we say all right well, what kind of action was it and The action was New user registered Okay, so it starts in an action it goes through the dispatcher and the store is listening for Events called new user registered and then what it will do is we're just logging it Okay, I received this event and then we're saying Establish a user using the credentials that came in on the action now note We've jumped through some hoops to get here but the action the store doesn't have to know anything about what's actually going on all it knows is Data shows up. I do what I'm told with it and then I send out a notification that something changed And that means that your store itself like our react components is very discreet very narrow Very focused just on doing what it does best which is update data and then tell people it updated data and What we're doing in this case We're gonna see a more typical example later of just emitting a change event in this case though We're not really changing. We're not mutating the state of anything after the user signs up What we're doing is just telling the view component that it was successful and the view component which is all the way back on sign-up form is Going to receive this event called sign-up success and In response to a sign-up success. We're going to navigate now something Here's where the react ecosystem gets a little bit Sometimes you wish there was a little more magic sometimes you wish things were a little more abstracted from you what we wind up having to do in our application is Grab an instance of the Yeah, in component did mount We are capturing a reference to the router This in full frameworks this kind of thing happens by default You just know that there's some service out there called location and that you can grab that service and do useful things with it In this case you have to set that up yourself You have to capture it you have to store it and then you can reference it later and actually do useful things with it so what we have done is now we can type in a user in a name and and hit create and Let's see did we actually jump ahead I think there may be one actual thing that just needs to That gets finished here So let's do that again Create a compile problem Yep, there we go. So this is part of life with react and in particular with compiling your jsx is that periodically You'll error out now. Usually. This is very useful. This gives JavaScript people a compiler To catch our bugs for us to catch our syntax errors This is actually very useful most of the time at the moment All it's doing is throwing an exception on the fact that something changed quicker than it really expected So we reload it Whoops now there is something Unhandled error event can't find module log in at oh did I add that as a can't find actions from Login, I think that this is one of the rough edges that we sometimes run into Because this code normally works beautifully And at least this part of it does there's lots of other parts that are totally screwed up What's that a reset of what? There isn't anything there are no changes So let's let's dump that let's create a new tab real quick IFF and let's try gulp again That's a good one Well, we'll demo in just a second after we move on to another Come another commit, but basically what we're doing is we're continuing on through the cycle We have successfully logged in took us a lot of work to log in We have figured out how to pass things through the cycle. We start from here on the login form We create an action we send the action to the dispatcher the dispatcher sends it to the store The source says okay, I've recorded this I've captured it so that you can use it and reference it later And then all the store does at that point is it says I did it I did what you asked me to anyone in the entire application Whether it's five components or just one who wants to know when changes happen. Here you go a change happened It's a it's as simple as that and then we listen for those changes So the new thing we need to do once we've done that is actually render The idea store so let's jump forward to commit and we're going to create a Yep, we're gonna start separating our actions into view actions and API actions just for clarity's sake and then Yeah, and then in the idea store we can start dealing with them So when the user renders ideas We we load up our ideas component the Often one of the things we want to do is we want to load certain data When the application bootstraps because it's an app-wide concern rather than a component specific concern So what we're doing is in our main GS JS file We're calling our API utilities receiving all of the ideas Now normally what we're doing then is kind of waiting around like okay I have to wait for those ideas so that I can do something with them in this case. There is no then there is no what happens next Our goal is that we want to fire events like this and forget about them You don't launch some rockets on the battlefield and tie a string to it and stand there with the string tied To your finger waiting for the rocket to land so you know what happened You just launch a bunch of them and you wait for the boom The event that comes back later is the boom, but you don't you don't sit there and hold on to it whenever humanly possible and So what's happening is that the the idea store so before we set up some listeners in the User store now the idea store is waiting for oh, yeah This event called add all ideas so whenever those ideas get done being retrieved the idea store will be there It'll receive this event and it can stash them away so that when we move on and begin Actually building out our ideas component that we can get it done. And so there's our ideas components It's starting to come together now Okay, so we this is all just basic boilerplates and so if we Log in now, let's see if we can get our gulp Yeah gulp is fine So if we log in There's our ideas component. It's there it loads and for some reason it doesn't like it. Let's We are serving on 3333 Let's open a new window just in case This is these are some of the rough edges that you sand off Once you get your router working properly There we go. So it's navigating successfully. We're seeing our ideas view But we need some stuff to put into it. So let's render that list The here in the ideas component We are executing the ideal list Okay, the ideal list is what actually contains the data and in this case we have delegated down to let's close some windows here Don't save anything. Thank you We want to open the ideal list We have delegated to the ideal list the job of getting state from the idea store We don't want the idea store to tell us when it feels like giving us state That would be a hard dependency that would be coupling everything instead We ask for it when we want it And in this case we also we tell the idea store Inform me when there's a change. Don't tell me what to do with that change Don't tell me I got this data so that you could do a certain thing Just tell me anytime it changed And so what we're doing is that at the very beginning Of the life cycle of this component we go and get the ideas from the idea store And anytime the store tells us that something changed This is optional. Some people will pass data a pass a payload on the event But ideally or not ideally but Hypothetically you're totally decoupled when all you get on the event is something changed request updates Okay, and then we reuse this function to get the data and to populate it And so all we've got is We're taking this dot state dot ideas. We're mapping it onto this new component called ideal list items And then we're rendering it out by this interpolation right here And we have to refresh log in And if I actually have data here yet. Yes, we have ideas And so our data now is Moving throughout the cycle. We've got multiple flux cycles going. We've got one going for users We've got one going for ideas as well we want to Yeah, we want to have a modal so that we can actually interact with these ideas We want to be able to click on this whoops and This is one of the downsides of how this is structured Normally, there's a lot conditional logic here to let you back in if you're logged in Um, we want to be able to open these up and see what's going on with them Hmm. Yeah, this is strange. I'm getting all kinds of compiler errors today um, and so what we're going to do is In the ideal list um In each we render our ideas Then each idea Each ideal list item We not only have the content this content here is what you're seeing in the view But then we have this modal that we're going to launch and this is a bootstrap a react bootstrap modal So we invoke this modal up here. We inject it Okay, no globals. We're just pulling this modal straight in We create um, that's a little premature And then we here's the structure for the modal which is going to show when the state says that we should be allowed to show it Now that's kind of messy. Um, we've just taken all this modal junk in we've polluted our ideal list item with that So even better if we refactor the idea modal into a separate component So that now all we have to do is just invoke this ideal modal here And the modal is a is a totally separate standalone component which can manage its own state And so hypothetically Yes compile works refresh and we can click on one of these And see the detail of of this idea And what we're going to do Then is we want to be able to um, we want to be able to do additional things with these ideas The point of this application. Sorry, I didn't explain that sooner This is for a kind of a team building. Let's improve our organization day So you can create ideas you can join an idea so that you can be part of the team That's why you see the team count over here the participants and we want to be able to join ideas and leave the ideas So what do you need in order to make that happen? To select an idea we're going to dispatch a bunch of events There's a new event called user joins idea And we need a button And that's basically it We're going to create a button that allows the user to join the idea When we click on that button, we're going to dispatch an action the action goes to the store the store Captures the fact that that user is now associated to that idea And then informs us that there's some something new And We want to then subscribe to that action in the um In the idea or we're creating a new component actually the user created idea And in the user created idea We're asking for We're checking the state we're subscribing to the user store And um, we're checking what is the selected idea? And so if we're still compiling we are we refresh Log in That's fine We can join this idea which will dispatch an action which goes to the store the store simply tells us there's something new We request what is it that's new aha? We have an idea selected now And it'll render And again it renders this component is doing some very very simple conditional logic here where it says if idea meaning the idea the user is selected is undefined um Well, if it's undefined give me nothing give me an empty div But if it is now defined Then render all of this this other content here And then leaving or editing the idea is um And creating a new idea are simply expansions of those those concepts We're just layering on more events more actions We can join the idea We can We should my apologies. I'm really getting some strange behavior after running through this many many times This is some of the things that I find still a little bit Uncomfortable about this eco. There we go. Um, we get some inexplicable errors That I don't see in other tools Um, so we can leave this idea which means dispatch an idea again Which just says the user left the idea. Sorry a dispatch an action the store Deletes the the selected idea Informs the view. Hey, by the way, there are changes the view requests. What are the changes? Oh, there's no more selected idea And so the idea goes away But nothing nobody in the whole chain of events knows how anybody else is consuming Those actions that information all they know is that it's happening And they have instructions about how to deal with What is happening? The last thing we can do Is we can edit And in this component In the selected idea component We have multiple versions of actually no, sorry, there's a new There's a new modal. This is why I said that this app is about 50 percent more complex than it should be We have an editable area and we swap that editable area editable details here with the static details And again simple javascript Is this dot this dot state dot editing is that true? Is it is it uh, truthy if it is Show me the editable content If it's not Show me the regular content. There's no magic there. There's no api there Um, but there are individual little components that can handle each of the details And just like before when we update what's in a form We capture the value we send it to the store the store tells us there's an update and then we request Well, what is that update? So there's a whole round trip that happened between Pressing save changes And having it be re-rendered into the view in a controller based in an mvc based model The controller would immediately assign what you just did straight on to the view In react we send it to the store the store tells us that there's a change and then we simply re-render We don't have to worry about keeping all of those things in sync Um dealing with that view based asynchronousness and that yes Yes, um if we import it. So the question is is the store visible to all the components And so we are taking advantage of the store Here for instance in the idea modal and so we just have to request it. We're importing it. It's a common js module We simply import that module and now I can reference it from within my From within my methods from within my render if I needed to So where angular gives us this sort of implicit dependency injection it says no no no don't worry about modules We got modules. We'll take care of it for you. Just give your service a name. Just give your controller a name And we'll worry about the rest The common js pattern Allows us or requires us to import each one individually Inject them into our component and what this means is that there is nothing going on in this component That I can't see up here at the top. There is no other magic. There's nothing hidden There's nothing else going on except I have a reference to the react library into these these two individual stores So let's get out of here. So actions are our discrete atomic bits of logic If something happens do these other three things they're as close as it gets to the controller The action based part of the controller the stores will sometimes have data manipulation logic that would also be in a controller We want to fire and forget. We don't want to Be hanging on to that rocket after we launch it We want to just send it listen for the boom and then do something based on hearing the boom It's actions are often but not exclusively where our api Api calls are triggered and then we just tell everyone the outcome. Yes Debugging what in particular? Well, there there is still a stack. There just isn't There are internal dependencies written into that stack There aren't assumptions, but the call stack is still there the call stack works the same way you're going to see you're going to see that the The initial view fired Bunch of methods that created an action Then that you're going to see a bunch of methods fire on the dispatcher Then after the dispatcher you're going to see a bunch of methods fire on the store Then after the store you're going to see it emit an event and you're going to see your View components receive that event So it's it's all still there in the stack It's just that you haven't written it into This thing instead of thinking you know having this monolithic controller Because we we think it's easier if we cram hundreds of lines of code into one place We think it'll somehow be easier to debug Instead what we can say is all I need to know is that events will come I um You log those events as they come in And then you say okay, I'm getting the event now and now I'll react to that event From js to jsx um the debugging I mean you can um It's like anything if anybody uses coffee. I don't like coffee But um, you know, you can just open up the compiled um Well for starters As you could see from these many errors that we were getting the jsx compiler will catch um many many many Um, so your runtime errors if you have any question about what those are I don't Usually what I want to say what the jsx compiler is translating Is not generally a source of complexity you're simply changing you're Almost exclusively what the compiler is doing is saying there's this action. There's this component called login items Invoke it and take these things I declared as attributes on my xml element and add them as payload And it's very good at doing that um, I have yet to see a situation where there was a a bug That was occurring in Transpillation Usually it's it's the consumer. It's the code that you write that takes advantage of those attributes and and makes use of them but what you can always do is you can um go into your um into your dist file and you can open up this js and um You know, let's say we're looking for the user selected idea So I can just look for a user selected idea and all of that code is here in its transpiled form And so you can see here instead of A bunch of xml elements here is React dot create element and uh same stuff just in a slightly less readable format But it's a very linear algorithm that that transpilation is not There's not much complexity there Yes, well, but um again generally I haven't at least run into situations where I really unless I'm Unless something is surprising me. I don't generally need to get into this Um, generally I can just look at what's going on in the original version that has the jsx and find the obvious errors there um Mm-hmm, I think that a lot of this goes to The general automation workflow to the the use of grunt and gulp Um in general and to any transpilation that we're doing whether it's a es6 to es5 or jsx to Uh jsx to react elements in general the Concerns are so narrow so simple so well defined That the things that we imagine we're going to wind up needing to track down in transpiled code Aren't opaque. They aren't things that are hidden in the transpilation. There are things that we can debug in the pre transpiled code in the original source um But that's that's dealing with an automation workflow and transpilation is a is a whole session by itself so the actions This one thing that we didn't point out explicitly is that we often use These things called action constants um And the reason is that when you're passing events around and action names It is so easy to miss spell the name of an action or event by creating a constant like this and always referring to it as um as a property name So here i'm dispatching it and i'm dispatching it by reference to constants that news are registered I pretty much guarantee i'm not going to misspell it if i misspell it i'm going to get a type error rather than um something that fails silently because it's passing an event throughout the ecosystem that has the wrong name on it And i wind up not getting the the behavior i expected So that's just the best practice The dispatcher is there's only one per app. Um, it's dumb The only clever trick it has is something called wait for and that's where you have two stores That are kind of sharing data. So there's a great example. Um, facebook provides a tutorial That's a chat application Chats are often threaded. Okay, so how do you how do you represent that? So in their case they created one store for the threads You create an object for a thread and then that thread has references to the actual messages The messages live over in this other store So anytime you update either a Message or a thread you need to make sure that they've happened the updates have happened in both places Before you begin to render wait for simply allows you to specify the priority And it's on an action by action basis So our stores about one per domain we can use it for things like modeling relationships All it does is take in changes Do the data processing logic? Let's say you're getting jason and you want to rehydrate those objects into real JavaScript objects augment them with new properties new methods something like that do that in your store Um Stores are smart about data and then dumb about everything else. They have no idea what's going on in the interface Um, note that unlike many frameworks flux has no opinions about models. It likes plain old javascript objects perfectly well And consider working with immutable data structures the whole concept of Your react components re-rendering rather than being mutated or updated is related to this idea about immutability If you're messing with something if you're injecting new things or pulling out one piece and sticking in another You've got all this potential for error for making mistakes So that's why with react we simply re-render the component from scratch rather than try to tweak it Immutable data structures basically apply the same principle to your arrays of data Um, and there is a recipe. There is a mix in for two-way data bindings. Um, it's actually a very simple concept It's not hard to implement yourself, but if you want to save four lines of code the the mix in will do it for you So we get powerful patterns here It's not a framework, but it is a really powerful pattern that makes it hard to mingle our concerns It makes it hard to have interdependencies. We create our action. We send it off We receive the action. We do something with it. We send off the result We receive the result. We do something with that at each point there's no there's no ties binding us and We're able to iterate on this piece on this store on this component Without affecting everything else as long as you conform to your api and pass events and these are universal events Um, everything still works The one I think concern Um, that I I still don't have a definitive impression on or my early impression over the last few months is You'll spend more time up front creating a lot of things than you would have with something like angular or ember Over the long term though the maintenance of those things gets dramatically easier So there's a crossover point where the additional upfront investment and the decreased downstream maintenance overlap Um, I think that comes in fairly quickly like something that you're going to be dealing with for more than even just a few weeks Um, I think you get your return on investment for for this pattern But I probably am not going to use it for rapid prototyping something that's only going to stick around for a week or two um for the time being I can still move a lot faster and angular and Angular saves you time in ways that become problematic down the road but That work great in the in the short term There's a lot of freedom. We work with enterprises a lot enterprises don't like developer freedom a lot We keep trying to persuade them to give their developers more freedom. What we're trying to figure out right now about react is Is is this environment structured enough that we can hand this over To our clients and have them be comfortable that their teams are going to be able to handle it And I don't think we have a final answer to that yet. We've done it successfully a few times But it really depends on the client. It depends on the on the environment Um HTML templating is going to stay around for a while, but I don't know at least in react land It doesn't have to and and I don't know how long And it's what I'm not what I don't think anybody is certain about is whether facebook is going to really be sort of the grand daddy Of react and specifically a flux the way that angular or google is with angular Um, and if that's even needed right do we need someone to steer? Do we need someone to make sure that that movement drives forward? The early indications are that the community is willing to pick up the pieces and create all of these other tools Redux reflux all The trick is just getting them to be as well documented and as well supported As they would be if they were all coming from the mothership So that's that's something that is going to evolve Over time and you know the best-loved components will eventually be better documented and better supported Um, this whole idea of virtual DOM. I think is oversold in some ways at least in terms of your life And how what react and flux mean to you? Um, you know in html document if you model the whole application in html That's a virtual DOM. It is a serialized DOM um So that's not the magic. I think what's far more interesting is the fact that we've decoupled the DOM and the logic And that it's immutable that we simply replace it Something change just replace the whole thing. Don't worry about mutating it. Don't worry about about dealing with it I think that idea is more powerful than what we often hear about in the articles that say Wow virtual DOM makes everything a million times faster than it used to be. Whoo um This stuff is what really changes our life is that everything is clearer and easier to think about And simpler to uh to update And the performance issue i'll let you guys read this offline um Is qualified there are certain things that react clearly does exceptionally well Um, but so many of these examples are about rendering 1500 rows of something Why are you rendering 1500 rows of something your user can't see 1500 rows? So being a library that makes it easy to render 1500 rows quickly is not necessarily a big advantage And this is just a guy who wrote a really good article about how sometimes plain old javascript will beat even react um for rendering 1500 rows Um, you can see actually react is getting significantly slower over time on mobile And it's those diffing algorithms that are doing it. So the pattern is more important than the hype Um, I wouldn't say that the number one reason to adopt react is speed. Although certainly the speed is strong It's there. It's good, but it's about the patterns Um And if you want to the good thing about a lot of people are pushing the idea Oh, well, you can gradually migrate to react. Um, just where it helps you with speed Um, yeah, you can gradually migrate to react you can You can blend in a a react component here or there But I think the the reason to do it is because you want to learn the pattern These are extras. Um, the those will be in the slides, which will be posted online And it is exactly 330. Um, it's time to go. I see the thumb. Yeah Thank you all very much. I'm going to stick around And anything else that you want to talk about that we didn't get to my apologies But that's why they're in the extras slides. Uh, we can talk about offline Oh, yeah, well, do we have if we have time? Yeah, maybe five minutes. Okay questions Yes, uh the the uh the slides you mean The code is in github. Uh, one of the first slides actually showed that both of the repositories Are already in github and are available. Uh, the first repo is actually just copies basically of other people's demos But with lots of comments. That's really the only value add there is all the comments The second one though is is more original and is available Stores are singletons. You mean are they kind of are they regenerated over and over again? Yeah, they're long-lived singletons They're kind of like If you think of the angular service pattern the premise there is that services are long-lived singletons And stores are long-lived singletons For ideas store So it is you know reading the idea store File, but then it doesn't have data Which you know One component has but the other component doesn't So how would you share data between two components which are sitting in two different routes? um I think that goes to implementation and I I don't have a good short term implementation answer But it they are they are singletons. They they do persist I'm I'm I've been using angular. I'm not yet used to react But it seems like uh, there are like some good bits in angular Yeah, there are good bits in the way that React has been implemented. So like would it would it be best to say okay mix and match like Take the view component From react which is very like composable And things like that and use the best of angular which is like routing I think dependency injection all that stuff like use the best of both worlds I think if brad green were here. He'd say check out angular 2.0 The um, there is a lot of similarity to that idea of what's best about angular plus the Componentization that react gives you and decoupling and fewer leaky abstractions That's the premise behind what angular 2.0 is going to be but it's not here yet We can't really see it and it's finished for him yet and in comparing contrast. I think that they Certainly react itself as an as atomic view components is very easy to mix into other patterns flux You know the broader flux pattern Um Is I think a stronger overall pattern than the current angular 1.x pattern Um And so ideally I would pick one or the other there So you can do it, but the long-term answer is it's it's not the race isn't over This is a marathon and angular 2 is coming other things are coming a really is coming Um, uh, really is much more template based for starters. Um, and we'll see All right, so I think that's all we have for the workshop. Thanks a lot, uh christian