React.js Introduction for People Who Know Just Enough JQuery
reactfordesigners.com
reactfordesigners.com
Imagine being solid at design, pushing pixels, using HTML, CSS. Then suddenly these program frameworks which are created by back-end programmers not visual designers appear and the ramp up for the average technical person is immense. For me it's been enough to turn me off them all together and make it a talking point that "my javascript skills fall off at X,Y or Z" so recruiters and employers know that despite being able to do a lot, I can't suddenly become everything UI and everything back end just because the title of anything "front end" is so versatile.
Yes I know those hybrids exist, but unfortunately there aren't nearly enough of them to fill all the positions. Not only that, but I'd argue that a lot of them who are hybrids, you're not going to get their best work from both areas if they are expected to deliver from both disciplines on projects. Not on the deadlines that employers will set at least.
And I suspect a similar problem exists in actual building architecture. Yeah some building designers are good at accomodating for all the variables of planning codes, but they aren't going to be (nearly as often) fantastic at aesthetics that somebody who works outside those constraints might be capable of. There's a lot of value in designing first, then put those styles of thinking together (designers and architects) separate people and from that point later in the process of creation you start solving the challenges like plumbing codes, metallurgy afterwards. Part of this is me complaining, but it's my attempt at experience of always being a crossover person and how you never really feel like you're honing a craft, you just feel like you're being left behind and not properly cultivating what you enjoy most.
var createItem = function(itemText) {
return (
<li>{itemText}</li>
);
};
return (
<ul>{this.props.items.map(createItem)}</ul>
);
...is clearly so much more logical than: <ul><li>{{item}}</li></ul>
Source: https://www.airpair.com/angularjs/posts/angular-vs-react-the...Also the angular equivalent would be
<ul><li ng-repeat="item in items">{{item}}</li></ul>
And the react-templates equivalent would be <ul><li rt-repeat="item in this.state.items">{item}</li></ul>
[1] http://wix.github.io/react-templates/ return <ul>
{this.props.items.map(item => <li>{item}</li>)}
</ul>;
vs. the Angular version: <ul ng-repeat="item in items">
<li>{{ item }}</li>
</ul>
The Angular template is more readable at the expense of ngRepeat's complexity. Neither example includes Component/directive boilerplate. The directive boilerplate is generally worse, because it requires a separate template file or an ugly template string, knowledge of the directives API itself which is baroque in the extreme, and $scope-wrestling (whereas JSX' scope is the same as JS').In my opinion reuse of the React component is more straightforward, you explicitly import/require it while in Angular you specify its providing module as an angular.module dependency, which has implications for config block ordering.
In React, I just create a renderNode method that's called by render at the top level, and renderNode on non-terminal nodes returns <div>{children}</div> where children is a map whose mapping function returns this.renderNode. The entire algorithm is grokkable at a single glance, and there's no need to create Directives to add any fancy features or special cases in the future. No need to read pages of documentation about ng-repeat and its intricacies; it's all just Javascript.
Yes, Angular "just works." But React "just works" the first time you try it.
<ul>{props/items/item/<li>{.}</li>}</ul>
But not interactiveBut there is still room for good designers who code; plenty of research, user testing and prototyping to be done before getting down the tech rabbit hole. A good team is multi-disciplinary and not necessarily composed of 'unicorns' only.
What I cannot figure out is all the harping on about "functional style". The React examples all felt more Smalltalk-ish to me than anything else (I suppose unsurprising given JavaScript's vague influences from Self). The use of closures doesn't really change the conceptual patterns much. Is it because the tutorial can only cover so much ground, or is it that since some of the primary buzz around FP was the management of mutable state, to the point that people now instinctively associate the idea with FP?
This is the main shift. It's very similar to how imperative programming is done in Java vs Haskell.
Furthermore, the input-process-output model can hardly warrant being called "functional" in of itself, unless you really want to overload the term.
The React way of independent handlers that trigger events which incrementally calculate state and update views, is, in fact, quite similar to how Smalltalk UI paradigms work, right down to the installation of an event handler resembling a message send operation.
If you don't believe me, check out the Morphic framework that Self uses to implement its environment UI. The similarities are striking: http://handbook.selflanguage.org/current/morphic.html
input-process-output is how pure functional languages (such as Haskell) deal with imperative coding. You push the imperative part to the top of the call stack and try to keep the rest of the computation pure.
JavaScript inherited quite a bit from Smalltalk, so you will find similarities like these in JS in general.
Flux supplements the standard React bubbling of events up the chain of components with a simpler, singular flow, making it even more functional.
In fact, you're equivocating the entire management and abstraction of mutable state as an inherently "functional" thing, which it is not. OO is just as much capable of factoring state as a virtual resource that you explicitly make transitions to and from and transparently or visibly share increments across object boundaries, as this is exactly what e.g. Self does with Morphic, right down to the same event handler structure. Just because one is a lambda and the other is called a method doesn't make a huge difference.
I'm saying that just about all of React's insights were done previously almost verbatim in thoroughly object-oriented environments. That some FP evangelists have a kneejerk hatred for it doesn't mean the mental gymnastics for insisting one over the other is necessary. They can be complementary.
Additionally I'm not sure where you're getting this "JS can't be functional" opinion from. Just because it doesn't give you compile-time or runtime guarantees, or because the syntax may be more clunky, doesn't mean you can't get these benefits by convention.
I never said this. I was talking more about the React architecture, specifically.
Though in general there is this phenomenon to grasp at any similarities and start espousing how functional a particular language/framework/library is, as if for street cred.
I would also never claim that React invented any of this. It just popularized this more declarative approach for building Web UIs
I'm not grokking the significance of why changing everything and having mutations is bad.
-E.g. use React (or Backbone, Angular, etc.): A real-time document editor, with many interacting components, with lots of real time updating of the UI. Definitely needed a framework like that, and it was great.
-E.g. don't use React, because in these cases it's a total Rube Goldberg machine (extra steps to achieve the exact same outcome): Basic web app with some ajax submissions, adding results to DOM type of stuff. Maybe small html fragments cloned, inserted by jQuery. No extra fancy client interactivity.
^If people claim you should use React for the latter (undoubtedly some will), they are very likely just people who follow trends to follow trends, or maybe don't have a ton of web experience and it's one of the few things they've learned and are sticking to. It's just so unnecessary (not to mention 100kb+ of overhead, & in my experience comes out to about x3 the amount of code). But yeah, absolutely use React if it's anything like the first use case.
regular old html and jQuery + ajax.
I was not making a judgement on the value of the approach, although I personally believe that this paradigm shift has a huge positive impact and is applicable in lots of cases. If I can choose between lots of computation intertwined with state mutation and a declarative approach where the mutation happens on the smallest scale, up the call stack, I will always choose the latter (of course, unless you have to mutate to gain performance).
Yes, if app is planning on being more complex, sure use Angular or Backbone or Ember or React. Otherwise, don't. Your pet projects sure, use it; if my team is billing clients, I've learned from experience, you're screwing them if you're not just using basic jQuery or even raw JavaScript which is a lot better to work with these days. If your reasons are only rooted in your abstract preference of design ideals w/o looking pragmatically at the situations, you're likely doubly screwing them.
Fyi this "paradigm shift" is like 8 years old, React is not disruptive, it's just another variation.
You can (and I do) view the React render as an idempotent projection from state to DOM, otherwise known as a template. React is a very fancy template system. You build your fragments (components) up into views, pass in your data, and render the entire page as if you're rendering it from scratch. It handles or provides hooks for all the situations I mentioned in the previous paragraph and React's internals ensure that it's reasonably performant by default. Having everything conceptually fully render from scratch every change means there's no separate handling for the initial render versus updates to the initial render (e.g. you have an accordion, render it with an ejs template but toggle it open/close by toggling classes). It makes the Backbone model work in a way that's easy to reason about.
A real world example: I've implemented (B2B, not something I can link) a drag and drop layout builder as a contract. The workalike they wanted, which I had also worked on but didn't design, was ~6k lines of node/class manipulation and mousenter/leave hit testing while my React version worked out to be around 600 lines, most of which were generating virtual screen position hitboxes for the various drop zones. Hovering/dropping in a zone changes attributes in a list of JS objects and the visual feedback is handled by the rendering code you'd need to draw the layout anyway plus another 20% for the drop previewing/hovering.
Most savings aren't as dramatic but in general you wind up spending less effort getting your views right. The LoC isn't always that much lower but it's template code instead of manipulation code. There are other benefits like component composition just working, server side rendering, putting all your app state in one place lets you do session recording and time travelling debugging but this post is long enough as is.
Consider a classic drawing API:
// stem
fill('green')
rect(146, 60, 8, 200)
// flower
fill('red')
circle(120, 30, 50)
// leaves
ellipse(173, 120, 40, 20)
ellipse(123, 130, 40, 20)
Now, imagine we first wrote the code for stem and leaves, than later added the code for the flower (in the reference, copied it from elsewhere). The code has a bug in it - the leaves are red. This is just one example: once you have a "hidden" state, you have to manage it. You always have to be aware of the effects that every line makes on the state and how the state affects the other lines. A "React"-like (simply declarative) API would look more like: stem = filled('green', rect(146, 60, 8, 200))
flower = filled('red', circle(120, 30, 50))
leaves = [
filled('green', ellipse(173, 120, 40, 20))
filled('green', ellipse(123, 130, 40, 20))
]
plant = [stem, flower].concat(leaves)
...
draw(plant)
The code is now referentially transparent, I could replace uses of variables by their values and nothing would change, since the functions have no effects. The effects are pushed to the edge of the code, in this case the call to draw which actually performs the drawing, or when React updates the DOM with the results obtained from a render method.That's nonsense. There have been data binding frameworks used for well over a decade in JS development - I know I wrote one in the early 2000s. You can't write a decently sized app in JS without developing something like data binding, unless you love busywork and bugs, or have zero prior experience of what came before in GUI frameworks.
Data binding is designed exactly to prevent the need to explicitly mutate all the views at every point that the model can change. Instead you write bindings that project the model into the view, and make the model reactive, so that changes to it propagate automatically. It's the same in any decently sized Backbone app - that's why the Collection and Model give you all these events.
What's new in React is the idea of cheaply creating a virtual DOM and extracting a set of diffs from it that can then be applied to the real DOM. I did something vaguely similar, again in the early 2000s, but the motive then was to reduce the amount of data on the wire (the server had a data-bound model of what was displayed on screen, but only sent diffs back to the client). It's a neat idea and an excellent implementation, but it's not original or groundbreaking.
As a big fan of react, I think that this isn't really a fair thing to say. I feel as though this statement implies that front end dev is not complex and therefore it surprises you that there is room for significant improvement. I'm sure that's not what you were thinking, but really, building complex imperative UIs with state can be very difficult, and react does represent a new step in the paradigm shift away from imperative development. Whether React is the future or not, components and composition are here to stay, and I think a increasingly large portion of the community is interested in writing web applications with immutability--all of which suites flux (and react) very well, and does not suite jquery very well.
React doesn't enable anything that you simply couldn't do with jquery and backbone, but it does make a lot of it way easier and reduces overall complexity by a ton, especially if you're developing with component structure and immutability in mind.
This is about more than just managing state.
If you're not familiar with FRP, then I think learning more about the theoretical side might help clarify why everyone is describing react as functional.
I have never seen React described as FRP, and a Google search for "React FRP" confirms that this is a heterodox belief and in fact it is you who might need to learn more.
I was thinking about react + flux, eg this line from the flux overview [https://facebook.github.io/flux/docs/overview.html]: "This structure allows us to reason easily about our application in a way that is reminiscent of functional reactive programming, or more specifically data-flow programming or flow-based programming, where data flows through the application in a single direction — there are no two-way bindings"
Anyway, I imagine people refer to react as "functional" because they conflate "declarative programming" with "functional programming."
We started with JQuery. It was fast and had a simple API. People started to learn JQuery more than they learned Javascript. You even had Stack Overflow answers that nudged people away from Javascript stating the robustness of JQuery's libraries (specifically how it worked the same on every browser).
Then, we realized that we did not want to set up our events as one offs. The result was very spaghetti code. Backbone came out of this. It was light and allowed us to modularize our code. However, it didn't really give enough structure so we switched to Angular. Angular was the holy grail. It did everything for us. Events automatically propagated state changes to our objects and automatically redrew our view afterwards. We didn't have to think anymore. It did the thinking for us.
Little by little, we started to realize that when you outsource your thinking to your framework, you end up getting stuck in crevices that your framework hasn't anticipated. In Angular, it's difficult to share state between controllers. It's outstandingly slow in that it redraws far too often. The thing that I personally was most sore about was the fact that Angular, similarly to JQuery became the new Javascript. Instead of learning how Javascript works, you needed to learn how to use Angular. This means that you couldn't just port in good Javascript code directly. You needed an Angular directive. Try using a simple charting library such as HighCharts. The examples don't work as is. You need to use the Angular version. It gets messy and all that modularization starts to work against you. It works against you because you don't have control over your javascript.
Here comes React. It takes a step back from the hand holding of Angular and just handles the rendering. You can design your Javascript classes and functions as you see fit. If you need to port in Highcharts, go for it. You can use the JQuery plugin if it suits you. All React really does is handle the rendering and re-rendering of your dynamic content on screen. It will also allow you to propagate events that will change the state of your objects, but does not do so in the same way Angular did. It gives you more granular control.
I suggest you try it out. The JSX syntax might throw you off at first, but don't give up. It's necessary for how React obtains its amazing speed. If you're just getting started, don't worry about the difference between Shadow and Virtual DOM.
Now what I do think is true is that Angular is a fairly complicated beast, which when combined with the poor standard documentation, makes it a non-trivial endeavor to learn and use properly.
As far as using services to communicate, I personally believe that its simpler to emit events. My absolute favorite way is how Mithril makes properties accessible anywhere. That way, you can just pass references around. It's not so important how you communicate, but the complexity of doing so. I believe that in your last sentence, you might have described the point better than I. It's a complicated beast. For that reason, you have to work within its domain. You can't invent your own way of doing things. You can't apply your trade in the way you want to. I suggest you play around with a React app and pay attention to the best practices of organizing your own javascript code more than what React itself does. It's refreshing.
Regarding services vs. events, I guess that's down to personal preference. I find a singleton service holding shared state much easier to reason about and maintain than I do events (for certain things, like shared client side session state...I certainly do use events when appropriate).
Regarding "doing things your own way", I guess that's a personal preference as well. Personally I like to nail down a few common implementation patterns that get the job done and then repeatedly use those and save my focus for the business problem at hand. I'm fine with the framework strongly suggesting or even requiring those implementation patterns as long as they work and aren't overly cumbersome.
From what I saw in the last Angular app I worked on, the ideas that services can work for this and that things can get difficult fast when sharing state across controllers aren't at odds.
EDIT: As per usual, I forgot the link: https://github.com/dahjelle/Programming-Worksheets/blob/mast...
Thanks.
Really well written as well.
I also like that it doesn't require anything beyond normal HTML to make templates and it doesn't require learning some huge framework just to bind a simple data-set into the page. You can also read through the entire code-base in an afternoon.
I think this kind of design should really be avoided, it breaks my user experience.
Good work.
Also: What's the deal with "the cow above"?
In scenarios with complex interactions, something like Flux is desirable, however small web apps work fine with simple JSON REST APIs.
The only drawback is that it doesn't support custom events out of the box. Instead, you have to manually create event listeners on elements on mount. As far as I can tell, there's no reason why it couldn't in the future though; Web component adoption is so low right now that it just hasn't been something people have complained about.
React is pretty new, once it gets bigger it'll also follow along too.
Yes, obviously. My company uses it for this. Personally, I don't know if AngularJS is a better alternative moving forward because it has a bigger community and companies such as Microsoft are integrating it on Visual Studio.
(Sadly being downvoted for saying this)
React will keep getting bigger, and AngularJS has no answer to React Native which I find pretty revolutionary.
I said React Native is revolutionary. It's the first JS framework that lets you build native iOS and Android apps. Key word here being "native".
React itself was designed as a UI library, purely to be used as the "V" in an MVC app. It's like expecting D3.js to do your AJAX calls. Unless it's a full front-end framework, there's no point trying to do everything.
It basically just gives you a view engine and then you have the flexibility to select what other libraries you want to supplement the rest of the app components.
This differs from other frameworks like Angular where you have to "go all in" and don't have the flexibility so that if something major changes (like when the Angular team announced HUGE changes coming in 2.0) you might get stuck with something you don't like. In this way, it's easier to switch out a part of your app as opposed to having to completely rewrite something if you use a full framework like AngularJS.
The folks working on Angular 2 are looking at interop with React Native's native shell so that you can write native apps in Angular (2) as well.
Yes.
In the meantime since asking I also came across restful.js (github [1], blog [2]) - it's new, but looks like a good framework-neutral alternative, if a little heavy at 27K minimised/uncompressed.
Edit: Actually, fetch.js + es6-promise-min.js = 26K, so not much in it.
[1] https://github.com/marmelab/restful.js [2] http://marmelab.com/blog/2015/03/10/deal-easily-with-your-re...
Technically? No.
React doesn't include the direct code to main API calls. You're still going to need to make the 'API calls' 'yourself', whether with jQuery or raw XMLHttpRequest or whatever. React comes into play when you have the data and you're ready do actually do something with it.
There's also a library to hook up React views directly to a Firebase (real-time JSON streaming) backend: https://www.firebase.com/blog/2014-05-01-using-firebase-with...
She makes 50% more than me, has cash in the bank, and loves her life.
All I have is picking on her javascript. And I'm not even really any good at it.
I think there's no reason to be correct when your goal is to buy food and pay rent.
With angular I can keep all my HTML in my HTML files. Is this normal or am I completely missing something?
http://courseweb.lis.illinois.edu/~hkim214/lis514/img/Dr_Seu...
My advice is to try it at least to the point where you've created a couple of components and rendered one inside the other. A component manages everything to do with how it works with props it's given and the state it manages, and how it renders is just another part of that concern.
One of the nice pros you get used to quite quickly is having your editor autocomplete event handler and data variable names, as they're all right there in the same file.
JSX is just sugar for React.createElement() function calls, the syntax of which otherwise gets quite unpleasant to write and maintain once you start nesting them to any degree (ask anyone who's used a DOM builder library for a complete app).
Once I started using React in practice though, it turned out to be pretty nice. It significantly reduces cognitive overhead when thinking about frontend elements. And if you're worried about your javascript file starting to look more like an HTML file, composition of JSX components helps break things up.
Even if I can't convince you that it's actually pretty nice, you can write React without using any JSX. Just use a live compiler http://facebook.github.io/react/jsx-compiler.html to translate any documentation into the vanilla JS equivalent.
Also i've never really gotten into all the string magic that angular templates use. ng-click="myEvent()", vs passing the event to the component as a property feels.
The Angular parser will go through the elements in the DOM and look for attributes it knows about like ng-click. When it finds ng-click, it will run the expression "myEvent()" on the controller's $scope.
A lot of these issues turn out to be things we learnt were bad ages ago and have forgotten why. The original context you learnt in might be sufficiently different or other factors might mitigate the underlying issue.
In the case of JSX - we were all told that to keep css, js and html separate - that inlines js and styles are bad. These things are all partially true but in a react.js project your components are usually tiny and there is always an inescapable dependence between js and html. It is therefore very different from when we used to see long html documents littered with onclick.
The real reason we keep "technologies" separate is so that we understand what realm we're working at any given moment. Furthermore, we can distribute responsibilities across multiple team members focused on different disciplines. Facebook has the kind of clout internally to force their designers to use JSX and inline styles, but many organizations do not have that kind of alignment.
In this case, you can split out that boilerplate into a separate, smaller component and reuse it inside as many other components as you need.
> By that logic we should be putting our data stores in the component, any translations required to internationalize the component, the database queries.
I respectfully disagree with your inference here - such functions can be abstracted and used by many components - in most cases there's no value in baking them directly into a component.
The exception to this is if the function is not abstract at all, makes no sense outside the context of the component, and therefore can't be reused. Then, it probably makes more sense to put it inside the component, rather than breaking it out into a separate file.
This is true of most if not all of the markup and styles used inside a component, which is why React encourages JSX and inline styles to be put directly inside the component as it's the only place they make sense, and the only place they'll be used. The markup, styles and component behaviour are intrinsically coupled, there is a lot of 1:1 referencing, and separating them out into separate files means you'll just be flicking between three files when working on a component, instead of one. Where there is 1:n referencing, well, that's when you should break your component into smaller, reusable pieces.
The reason like Knockout.js because all the magic happens in a standard data-bind attribute, no funky syntax or paradigm shifts required. A purely functional solution like React seems like it's good for making games. Beyond that, for most sites, I think it would be more work to use React for little to no gain.
However it has a few issues.
1. Wrapping everything in observables is a bit annoying. Subtle issues can arise here in there especially if using the mapping plugin (which you kind of have to, it makes the process bearable).
2. If you start to have a lot of bindings on a page (a few hundred) performance degrades rapidly and there is a ton of DOM thrashing. Part of the problem is that a binding places an event handler directly on the DOM element. But there is also the initial load "flicker"/DOM thrash which for a significant page can take a second or two.
3. There are lots of workarounds such as rate limited observables, etc... But these are applied individually and become very tedious. They do not solve the entire problem either.
React solves all 3 of these so I can see significant benefits there. I have not switched myself but am experimenting. I do think Flux, Stores, etc.. are very overkill and actually poor architecture. But thankfully there are many alternatives cropping up which are much better.
React.js seems like it could be a good core for something like those alternative frameworks that you mentioned popping up. Aurelia looks interesting to me, but I don't think it uses React by default.
http://apidock.com/rails/ActionView/Helpers/TextHelper/conca...
http://thepugautomatic.com/2013/06/helpers/
http://guides.rubyonrails.org/form_helpers.html
https://github.com/rails/rails/blob/dd7af2c413a06ea44e50abf0...
Also, there's the authors very well-placed point that adding a new feature may lead to css query refactoring, eg. when $("textarea") doesn't cut it. I find html refactorings to be nb 1 cause for breaking progressively enhanced solutions like this one, probably bc I suck at naming elements.
Lastly, it should be noted that this refactored solution does not contain all the features of the final react solution.
Just a small nitpick I had after thinking about the reasoning behind why the OP had disabled the button in JS rather than the HTML in the first place.
One thing, the page loaded constantly itself, after reading half through the tutorial (3-4 minutes), I had about a hundred entries for the same page in the tab history. This makes the website aweful.
Edit: I think it has to do with JSBin. I reported the issue here: https://github.com/jsbin/jsbin/issues/2464
Edit: It might have to do with JSBin. I reported it here: https://github.com/jsbin/jsbin/issues/2464
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 14.10
Release: 14.10
Codename: utopic
$ google-chrome --version
Google Chrome 43.0.2357.132
[1] https://imgur.com/JN5PlqNThere are ways to avoid it, but I'd encourage you to give it a while before looking for a way out, because almost everyone I know who had that initial reaction has come round to it.
Please keep reading! It's really more than that! I wasted 2 years by not spending 20 more mins.
Wasn't React developed as a tool to manage complex data flow patterns inside of a big web app like Facebook ? Why does your average JQuery developer need to know or care about this whole new abstraction layer ?
Even though I've seen it a 100 times by now I'm still amazed by how fad driven programming culture is and I feel like this is a perfect example : React - come learn this complex peace of technology to solve problems you never had (and probably never will).
In fact if you look at the URL the site is called reactfordesigners.com.
You would want your designers to write frontend code that is complex enough to require React ?
The way I've worked with designers is they create sketches and prototypes just to demonstrate the concepts with whatever they are familiar with and then developers turn that in to actual maintainable code with feedback.
Unless you're working at a really big shop, designer these days is almost synonymous with UI/UX engineer or front-end engineer. Considering the target audience is JQuery users, React is not too far of a jump and doesn't have to be restricted to "complex" websites.
At the point where you actually need React you also need to understand software engineer or you're going to get a mess no matter what the framework is.
With Web design, I started with simple HTML sites, learned CSS, then learned some JS to manipulate the DOMs I created.
Having run into some of the jQuery pitfalls that the author describes, This tutorial meets me where I'm at and takes me to a new place, using incremental, concrete, and practical examples to show me that React is a logical extension of JS in certain use cases.
Designers are visual people, so being able to see each step along the way and telling me why it's important is a really big deal. I have some projects now where I'm changing state quite a bit, and I can now see where React would be really useful. Designers also tend to get into the web coding stack from the front end first, so I think we end up thinking about coding a Web site in a really different way than back-end developers with a background in software engineering.
I feel as though the move from raw JS to JQuery is similar in significance to the move from JQuery to React. So in answer to your question, I would say a dev who learned React would be more appealing as a hire and as a colleague, and it'd be well worth the investment for any future career.
The same thing is true for jQuery -> React. If you're a front end designer who does some programming - you need to learn the DOM and CSS, jQuery is just a simple tool to leverage that more easily.
React is a fundamental change that requires a lot of relearning and more importantly the benefits are questionable unless you're dealing with the scenarios it was designed for. You need to have experience with existing tech (that is way more intuitive, like two way data binding) to see what problems it solves - that's not in the domain of a jquery programmer.
I also wouldn't call people who "just know jQuery" devs but rather designers who know how to code.
In all seriousness, I've already had to rewrite a codebase because an inexperienced programmer (less than 2 years professional) chose it for a use case that wasn't even appropriate, and he did a terrible job implementing it correctly. My team that took over wasn't happy.
If programmers didn't do stuff solely because it's cool, then that would have been a day back on that project.
(And yes, there are cases where React is a bad choice, like with said project)
jQuery works just fine at small enough scale. Once you out-scale jQuery you will have problems that won't be solved just by using a different view library - you need to understand software engineering - which is why everyone who actually uses reacts also uses things like Flux, etc.
My point is jQuery works for what it's used, getting people to switch to React seems like a fad because "the cool kids are doing it".
Novice programmers don't have the perspective to understand that the latest hot library may be old news in 6 months, and how the old adage of "hold a hammer and everything becomes a nail" can impact a project.
A year or so junior programmers figured out how to add Angular as a dependency into every single project whether it was needed or not, now people are teaching them how to do the same with React. The constant parade of new JS frameworks combined with the ease of package managers & compilers is creating a nightmare scenario when it comes to project bloat
But my javascript hipster friends all claim that this is wrong and stupid and that I shouldn't use jquery because of some abstract reason that nobody ever seems to be able to articulate to me.
There's nothing wrong with just using jQuery. For many, many applications/projects it's a great tool and does everything you need.
What happens as a project/app/site grows is that you add more and more and more jQuery to a single file and it starts to get hard to maintain (hard to find what you want, hard to change something without something else blowing up, hard to navigate the files you're using). Frameworks like React, Backbone, Angular, etc were made to drive large, complicated, often single-page applications where you have massive amounts of interacting code and want to generally simplify what you're writing and how it's architected.
So, in the end, these are meant to help you organize code, be more productive, and have a more coherent architecture. That's the idea, at least. The tweetbot example here is simple because you're just learning so, if this is the only thing you're building on a page, it probably makes more sense to just use jQuery.
I think the typical road from jQuery-only to using a framework is your apps get bigger and you start to think "this is hard to maintain." Then you see an example of a framework doing something that would really help your process and see how it could improve the code you're writing. You try it out, it makes the process easier/more enjoyable, and you continue learning more. Or it doesn't and you swear it off.
AFAICT, these frameworks grow out of a person or team that figures out a more productive way to write code for what they're working on. That becomes a boilerplate they use, then grows into something they think would help others out. Then it gets a name and we all argue about it. In the end, it's just one person's/team's/company's idea of how to write code better, which may or may not work for other people/teams/companies.
1: you can do without jquery, and therefore you should. if all you need is $('#my_id') then it's overkill and it's better to save on download speed by leaving jquery out. See http://youmightnotneedjquery.com/
That said, jquery is a powerful tool and it's widely used for a reason.
2: unrestrained use of jquery, if it's your only tool, can lead to code that is hard to understand, and easy to get wrong. if any part of your code can modify any part of your page, then it is a good idea to retreat from that and be careful/organized about what you do, and when/where you do it. that organization is what JS frameworks try to help with.
you may or may not find your life is improved by such frameworks, depending on what you're doing.
The biggest issue is when you take something like jQuery and try to have a multi member team working on a significantly complex and large application. It quickly gets out of hand, messy, and increasingly difficult to maintain. This is without taking into consideration the issues that arise if the developers on the team don't have a basic grasp of how to write jQuery code that still performs well with large amounts of actions/DOM manipulation.
Many interviews for front-end positions also want to make sure you don't only know jQuery, but at least have some grasp on DOM traversal/manipulation without crutches like jQuery.
A lot of the bashing though, is really just from people with a superiority complex instead of logical reasoning. Or it's just people who repeat what they hear, kind of like one of the largest hate trains of all: PHP. Kind of like the story about the monkeys, bananas, and a ladder: http://www.wisdompills.com/2014/05/28/the-famous-social-expe...
[0] https://precursorapp.com/blog/clojure-is-a-product-design-to...
React is more like the view-lib of a framework. I like them both (also ember, knockout, backbone) and unfortunately think the battle isn't decided yet. Will take some time if ever...
Complain to Steve Jobs(1), for killing Flash/Flex, as you could to client-side apps with desktop performance, without the hassle of Cross-Browser testing and so on... In my opinion the concepts of Angular and React+Flux are heavily based on the features this platform provided.
(1) IMHO the Only good thing he ever did (for the web), as it forced the proprietary software out... but led to the great Framework-War :)
P.S.: Also Actionscript 3 was ECMAScript(Javascript) plus Classes, Types and more... ( I wondered about which Version that was latly and found out they implemented ECMAScript and extended it with features requested by users.)
Cheers
This may be a bit late, but I would LOVE for someone to do this for JS in a Rails App (or even CoffeeScript). I am desparately searching for good tutorials for people that are "borderline-decent" at jQuery but are Rails devs. I can't find any.
I understand, in theory, how to render some JS on a view and all this good stuff - but once you go into creating a UI that feels like a modern UI with lots of lil AJAXy elements...it can become a pain REAL quick with a bunch of `...js.erb`s all over the place with no seeming pattern to them.
So I would love if someone had a tutorial just like this, for how to create a simple and sexy app that looks like an Angular/Ember app but just using CoffeeScript/jQuery/vanilla JS.
Anyone know of any such thing?
Have you seen this? http://todomvc.com/ You can try implementing a backend in Rails for the jquery example. https://github.com/tastejs/todomvc/tree/gh-pages/examples/jq....
The JS file shows how to organize javascript code - https://github.com/tastejs/todomvc/blob/gh-pages/examples/jq...
Also unless you really like coffeescript, stick with javascript. If the syntax is bothering you, you can write in ES6 (next version of javascript) which has nicer syntax and use babel to convert to ES5
1. https://gist.github.com/danielgtaylor/0b60c2ed1f069f118562
Also, I do write JS in separate JS files - but my understanding is that when you want a response to be in JS, don't you have to use a corresponding `...js.erb` file to handle the action/response?
How else would you update the DOM after the action has been completed?
The json the code fetches is static but it can be served by a rails app. The DOM manipulation gets painful which is the reason people adopt JS frameworks.
I wrote about it a bit here [1].
Unfortunately... It does kind of assume you're familiar with CommonJS and a bit of the ecosystem.
[0] http://github.com/cesarandreu/web-app
[1] https://blog.cesarandreu.com/posts/a_reasonable_starting_poi...
I did 4 years ExtJS and 1 year Ember. React was totally different but rather nice to work with. The API surface is so much smaller.
TodoMVC was a great effort. But unfortunately, the actual Todo creations are not well documented (for beginners to figure out how and why certain things were done).
Of course there are great alternatives with similar workflows (mercury, etc).
This tutorial is absolutely awesome.. and I think the deep dive is worth it for larger apps too.
It was a nice overview of React to me.
I'll take the time to learn something new when it is truly groundbreaking but until then I care more about the end product than what was used to make it.
In all seriousness I typically work with a lot of designers; asking them to update markup in JSX versus HTML is simply not possible. It's not because they can't figure it out but it makes it more difficult for them to quickly test and they typically break JavaScript in many, unexpected ways. While I'm fine with the UI and business logic separation where UI can contain markup _and_ scripting, I don't think the answer is this awkward solution of shoving HTML into the scripting.
The flow typically looks like this:
1. Create conceptual wireframes
2. Build static UI components (typically in sketch)
- This step helps us define the look and feel of the product before jumping into code. However these are not full page mockups. It's more like an internal UI kit, and for the most part, it's fairly standard across products. So we don't have to update it often.
3. Build the styleguide from the UI kit in Sass (within the framework) - Again, this is fairly standard so it's mostly templatized. We have an internal UI styleguide that's built already. So most of the changes per product are minimal (they're mostly small tweaks to give each product more character).
4. Build the prototype (within the framework) - Since we use a template for each new prototype things like routing and more complex Angular concepts are already set up. Because of this designers aren't forced to approach the steep part of the hockey stick. They can stick to the view layer.I ask because I'm a backend (Django) dev looking at upping my frontend chops (having previously used jQuery and ajax to glue things here and there), and I'm overwhelmed by the choice of frontend frameworks at the moment. I'd love to see how a big jQuery project is set up.
Particularly terrified of making a time investment and finding out that my chosen framework is no longer the hotness of the week. Because, support and community and stable API's count.
Based on that experience, I smile a little when I see people claiming that you can’t build significant web apps without a modern framework. Of course you can. The architecture for the app I mentioned has something close to a traditional MVC structure, uses a simple observer system for keeping everything in sync, and generally follows good modular design practices. Nothing about writing code for a web front end magically breaks all the UI ideas we’ve been using successfully in other environments for decades, and people have used those techniques to build UIs vastly more complicated than any web app ever written.
That all said, it’s also true that as the interactions between different parts of models and the rendering of views becomes more complicated in a UI, writing manual code to update the DOM via jQuery becomes tedious. I thought this article summed up the problem quite nicely with the code snippets and diagrams showing potentially SxR relationships between state and rendering when you manually and directly update the latter, compared with S+R relationships when you isolate each side with a good architecture.
So, I’d say the more interesting question if you’re building a not-small web app is whether you are better off building your own architecture or reusing someone else’s. That has the same trade-offs as any other framework decisions in programming; again there is nothing special about writing a web-based front-end really. On the plus side for a comprehensive framework, you get a lot of basic things much quicker than writing them yourself, and the popular frameworks have huge ecosystems built around them so a lot of not-so-basic things can be had relatively easily as well if you need them. On the minus side, in practice you will forever be constrained to work as the frameworks want, which can become a heavy burden later on if you do need to do things that aren’t a perfect fit, and you are locked into external dependencies with uncertain long-term support.
Something I find interesting about React is that although it’s often compared with big front-end frameworks like Angular, it’s really closer to a library than a framework. Fundamentally, you use React to do exactly one job: manage the rendering and events within a specific part of the DOM. It’s agnostic about where any underlying state comes from, what triggers updates to that state, what you’re doing in response to any events, or what you’re doing anywhere else in the DOM. The entire API for React doesn’t quite fit on a single screen, but a minimal working example only depends on three functions that feature in React’s defined interfaces, and even in real production code you probably won’t use more than a handful.
So if you’re the kind of developer who is concerned about bloat and dependencies but also wants to use good tools instead of reinventing the wheel, a library like React is probably a reasonable compromise between retaining control and long-term flexibility in your code but also automating things you really would waste quite a bit of time on otherwise. I suspect this balance is the main reason why it seems to attract favourable comments from a variety of developers, including those who generally don’t like the heavier frameworks and all that comes with buying into them.
Just by way of completeness, probably the most controversial aspect of React is the way it winds up with its version of HTML templates being embedded directly within the JS code (with some optional but convenient syntax that a preprocessor turns into real JavaScript). You aren’t likely to be getting one person/team designing your mark-up and styling and then having a separate person/team implementing your JS coding if you use React. In this respect it does also come with a degree of lock-in, because transferring those mark-up/template assets to another rendering library or framework later would be a chore. However, that’s somewhat true for most other template-rendering tools you might use as well, because they all tend have their own syntactic quirks, so I’m not sure it’s really worse than other reasonable choices you might make.
So in summary, you certainly can build web apps using manual, direct DOM manipulation via jQuery and the like, but you will also wind up inventing much the same kind of tools that many of these frameworks provide to a degree. There is a balance to be struck between retaining full control and flexibility vs. using good tools, just like any other programming with libraries and frameworks. As for React specifically, it really sits closer to the library end of the spectrum than a lot of modern JS frameworks, so if you do want a modern tool to help with rendering and managing events in your DOM but don’t like the big framework lock-in, it’s probably worth a little of your time to investigate whether it’s a good choice for your project.
I thoroughly disagree. There are a lot of challenges and opportunities with web apps that you do not have in the same way in other UI environments. Having a way of enumerating different states of the application, and jumping between those states (URIs) is just one.
Can you suggest a few others? I don’t see how the issues that arise with the example you gave are any different to things like parsing command line options or acting on shortcuts in native UIs.
Most web apps treat different routes as different screens, effectively, to use a piece of jargon from a bygone time. A URI is usually just a parameterized screen; IDs in the URI determine which bits of data the app is viewing / editing, no more or less than parameters to a Visual Basic or Delphi form.
Frameworks are for programmers who must collaborate.
Indeed the old web dev write once, pass it to the client and never see it again has quite a bit of difference in requirements to the large scale robust web application that needs to be able to survive a long period of iteration and maintenance.