Honest question here from someone new to React. Isn't the way it mixes in HTML, CSS classes and JS altogether something we were trying to get away from a few years ago? It feels a bit like old school ASP! I'm not trying to be flippant, I just was always taught about separation and mixing HTML markup with JS logic seems like we are going the other way.
> Isn't the way it mixes in HTML, CSS classes and JS altogether something we were trying to get away from a few years ago?
That's a best practice for web sites. If you're making a website (where every page has roughly the same look and structure, but just different content), then it's probably a good best practice to have.
It all went haywire, however, when using the web for applications. While well-designed applications also have commonalities to them (button styles, margins, etc), the various screens and dialogs in an application vary way more in structure than the various pages on a typical informational web site tend to do.
It turns out that separating logic and presentation in web applications the way you would on web sites is a very bad match. You simply end up putting logic that is very closely tied together in three different places. E.g. typical jQuery code that falls apart the moment you change either the HTML (turn a div into a span, whatever), or the css class names, or the jquery selector/handler code, all of which is located in different files deep in a different directory hierarchy. For each single widget in your app (button, dropdown, LoginScreen, etc), it's much better to put all that code together.
And that's what React lets you do.
(note that this means that you really do want to tie your styles closely to your react components too - either inside the JS or with e.g. one .sass file for each React component)
> It turns out that separating logic and presentation in web applications the way you would on web sites is a very bad match. You simply end up putting logic that is very closely tied together in three different places.
As a web developer for the past 10 years I can't disagree with this more. It wasn't the easiest thing to accomplish maybe 5 years ago but it was always doable and now with web components it's incredibly easy.
React is cool but I wouldn't call separating logic and presentation bad. I would call that a best practice.
I wouldn't call separating logic and presentation bad. I would call that a best practice.
Even if that is true, it is not clear that trying to separate HTML, CSS and JS necessarily achieves a useful degree of separation between logic and presentation.
In "traditional" application development, we have long recognised that things like keeping the underlying data isolated from any particular presentation or interaction style can have advantages. However, you wouldn't find a lot of people arguing for creating a dialog box in some visual design tool in your IDE, writing separate code in a programming language to populate its controls and respond to interactions with them, and then somehow trying to join the dialog and the code up while keeping everything at arm's length.
Modular design has always been about keeping related aspects of a program together and minimising other dependencies. This means you can do useful things like changing one part of a program without running into surprising or uncontrolled side effects elsewhere. But if you have different aspects of the application that inherently do change together, as is often the case with HTML/CSS/JS in a web app, there is little benefit to trying to separate them for dogmatic reasons.
> Even if that is true, it is not clear that trying to separate HTML, CSS and JS necessarily achieves a useful degree of separation between logic and presentation.
I agree and this is why I continued to iterate OP's word usage of separating logic and presentation. Separation of HTML, CSS and JavaScript isn't always useful or straight forward but separating business logic from the user interface is incredibly important, in my opinion.
Separation of HTML, CSS and JavaScript is more of an organizational thing in my mind. JSX makes the syntax awkward and more complex in my opinion especially when you're working with a group of designers who are constantly tweaking styles, element layouts, etc. But for a team of only developers it's not so bad. Still I personally find it easier to simply avoid JSX either way.
Separation of HTML, CSS and JavaScript isn't always useful or straight forward but separating business logic from the user interface is incredibly important, in my opinion.
I agree, but if we're talking about using a front-end framework like React here, wouldn't that mean we're only talking about the UI parts of the application anyway?
Personally I'm not a big fan of either big frameworks generally or some details of React in particular, but the people behind React do make reasonable arguments in favour of their more component-based separation of concerns.
> I agree, but if we're talking about using a front-end framework like React here, wouldn't that mean we're only talking about the UI parts of the application anyway?
I don't think so; when working on code for a web application there is always code, styling and html elements that deal ONLY with the presentation side of it but then there is also code that handles talking to the backend, negotiating with web sockets, etc. That code really needs to be separated and what I'm referring to.
> the people behind React do make reasonable arguments in favour of their more component-based separation of concerns.
I love component based separations and I get the feeling many of us are talking about similar things.
I don't think so; when working on code for a web application there is always code, styling and html elements that deal ONLY with the presentation side of it but then there is also code that handles talking to the backend, negotiating with web sockets, etc. That code really needs to be separated and what I'm referring to.
Right, but React isn't normally used for things like back-end comms. It's often loosely described as being for the "V" in "MVC", which makes sense given the whole declarative specification of DOM content angle and the one-way data binding style.
As with all technologies it matters how they are used; I simply stated web components make the separation easier than ever before but that doesn't mean the same can't be done with JSX.
I think it's very important to keep the interface away from the logic. Creating components in React that only drive the user interface isn't bad but it's not as straightforward as something native like dealing directly html and css. I've worked with many designers who are awesome at styling and making pages look great but when they have to edit any type of scripting or something outside of HTML / CSS it's a whole new skill-set they need to learn to be effective (a skill-set they don't really need that the majority do not have).
Some components turn out to need logic though - consider some of the Twitter Bootstrap components that rely on JavaScript. They would not work without the JS.
I do agree that there are concerns when it comes to having people edit certain aspects if they specialize, I have seen similar things in the past. I would say that this depends on the people you work with.
Depends on what we're referring to when we talk about logic. I consider the user anything the user directly interacts with while with the logic I was mostly referring to business logic. It's fine to have interactive pieces that need JavaScript as long as they're kept away from the business logic.
My rule of thumb is: the user interface and the business logic should be separated to the point where you can completely replace the business logic without touching the user interface and vice versa. That's the separations I strive for and it's incredibly helpful when a designer wants to completely rearrange everything about the user interface because only one area needs changing.
I agree with this. I also think it that keeping logic out of views is a good idea, but I think that like many one-liners, there is more to it than just that.
I think that there is a certain amount of logic that is necessary in our views. Otherwise, JavaScript would not exist. Manipulating the DOM via the vanilla API or via jQuery is only hiding that logic in another file. The logic is still there, and calling it "separate" is not useful, in my opinion.
I like the way React bundles this view-specific logic and the markup together. Now I don't have to look at some HTML and wonder if some JavaScript somewhere is messing with it.
CSS is another matter entirely. CSS doesn't change behavior and is another concern entirely, so I do still prefer it to live in its own files rather than being inline. React doesn't change anything about this, and that is fine by me.
Is the distinction between web sites and web apps really valid, though? No matter how dynamic your site is, you still have certain responsibilities to your users, including giving them the best user experience you can, but also things like accessibility, sane SEO, bookmarkable resources, and, in the long run, maintainability. Is a highly dynamic site really a "get out of jail free card" for best practices?
> Is a highly dynamic site really a "get out of jail free card" for best practices?
No, of course not. React proposes to replace one "best practice" by a different one. In React, the best practice is to divide your application up in a deep hierarchy of components, each of which adds one single little layer of abstraction over the other. Then, put all the logic and presentation that's relevant for that little piece of abstraction together inside that little component.
This way, you have very good separation of concerns - all "Button" stuff is together in the Button component, all AreYouSureDialog stuff is together in the AreYouSureDialog component (which in turn uses Button components), and so on. Because components can only interact with each other via props and refs, you also have very fine-grained control over the interface: it's difficult for the programmer of a parent component to influence the behavior of the child component any further than by the interfaces that the child component explicitly exposes for that (= props, and public methods for use via refs).
How is all that a "get out of jail free card"?
I've found that this design principle works very well with teams, even with junior team members. I've seen people who had never gotten further than building 10000-line CSS files with all kinds of horrible hacks let loose in a React project. After we explained the component principle and made an example component to easily copy&paste, they independently and without further encouragement started making React components for each little possibly-reusable part of the application. Buttons, frames, dialogs, cards, lists, you name it. React really makes it easy to make well-structured code and difficult to make things a mess.
I don't see how and of this impacts any of the responsibilities you mention (good UX, accessibility, etc) so I can't respond to that part of your comment.
it's difficult for the programmer of a parent component to influence the behavior of the child component
You seem to focus only on the few drawbacks of CSS inheritance and to ignore its biggest advantages like you don't have to write declaration for every and each element on the page and rely instead on inheritance for props to cascade properly.
Yeah sometimes undesired consequences occur on elements but it's easy to remedy the situation if you know what are you doing but by moving all the presentation info to your logic layer in development, and then littering the structure/content layer i.e. HTML via style attribute in run time, this is unacceptables and can't be seen as progress for the industry in any way.
> You seem to focus only on the few drawbacks of CSS inheritance and to ignore its biggest advantages like you don't have to write declaration for every and each element on the page and rely instead on inheritance for props to cascade properly.
This presentation explains what problems React inline CSS solves
Could you please summarize in a few sentences what are these probs this approach deem to solve?
Because I have seen demos and talks from React people and I was appalled at their neglect of best practices and bending the rules just to push their product and technologies on the community
My main complaint with CSS in JS is that a strict naming convention solves a lot of the problems without coupling styles in application bundles. Basically, I don't want to invalidate my JS bundle just to include a new visual theme.
Luckily, you can use CSS best practices with React.
The problems mentioned in the presentation, followed by some CSS-friendly solutions --
1) Global namespace: all selectors are global
Use a naming convention.
2) Dependencies: no way to specify that a block of markup depends on a particular CSS module
Use a build process and a naming convention that includes a component name.
3) Dead code elimination: difficult to determine when styles are no longer needed
Loop over components and extract CSS component names from class attributes.
4) Minification: can't minify class names in markup
Not a bottleneck, nobody cares.
5) Sharing constants: can't share constants/variables with javascript
Use rework/postcss.
6) Non-deterministic resolution: loading styles asynchronously can result in different results since specificity assumes later rules should override earlier rules and async load order is arbitrary
Use SUIT CSS to prevent collisions and normalize specificity.
7) Isolation: base component CSS can be trashed by authors of subcomponents, making it difficult to change base CSS.
Reduce responsibilities of base component CSS. Encourage use of modifier classes. Ban tag selectors from component CSS. Use a SUIT CSS compliance checker.
I use SUIT CSS with React and couldn't be happier.
Seriously, all these points sound very fancy and I suspect that they bring unequivocal productivity gain to the dev environment but my main beef with FB or any other org is that they push this workflow or other methodologies as universal best practices or even distort reality and claim that mixing content/presentation/logic is the only right way to "separation of concerns" and all what you knew before about this topic is a hoax and big lie.
Why are you looking at this as "bending the rules" instead of as creating new rules for a new way of building web applications? Just hand-waving "best practices" doesn't actually mean that something is best practices if someone else comes up with a better practice.
You guys have to convince us first that mixing content+structure/presentation/logic is the best way to go forward in web development for the following reasons 1,2,3 ..etc.
I'm all for progress and challenging/questioning previous norms or traditions. I hate dogma and dogmatic people like the next guy but I need first to see improvement in the new thing before going adopting it.
What I see now frankly is the opposite of progress. I see people advocating for dispensing of "separation pf concerns" & "progressive enhancement" in the name of "progress" and "modernization" but in reality it's just a lame excuse to regress to a state of affairs that we guys fought too hard to combat it and bring awareness to the community of its pitfalls and shortcomings.
>You guys have to convince us first that mixing content+structure/presentation/logic is the best way to go forward in web development for the following reasons 1,2,3 ..etc.
There are a million articles and talks that provide exactly this. If you don't find them convincing that's fine, but don't act like no one is providing them.
> I see people advocating for dispensing of "separation pf concerns" & "progressive enhancement" in the name of "progress" and "modernization"
If that's what you see then you're looking in some weird places. The drivers behind React aren't just vague ideas like "modernization", they're the real-world benefits people are seeing when developing and using these new ideas. You're doing a disservice to everyone by fabricating the reasons behind these ideas just because you don't like them.
>in reality it's just a lame excuse to regress to a state of affairs that we guys fought too hard to combat it
This really just seems like a stodgy "get off my lawn, kids!" approach, which is at odds with your "I hate dogma" statements. Do you honestly believe that people are pushing in this direction solely as an excuse to regress things and make it worse? Even if you think that it is "regressing" things, you can't possibly be so conservative and entrenched as to actually believe that is people's goal, can you?
There are a million articles and talks that provide exactly this. If you don't find them convincing that's fine, but don't act like no one is providing them.
If you have been asked what's the most important convincing reason to switch to React, what would be your answer?
Please no mention of web apps vs web docs. We're already established that.
- It has been all about progress and modernization all the time. Progress in terms of productivity gains and speed was the motivation behind dropping jQuery centered architecture and going for an MVC framework instead and it's what's motivating the spawning of these frameworks as well. I don't know why this point is contentious one for you.
Do you honestly believe that people are pushing in this direction solely as an excuse to regress things and make it worse?
I didn't say that and I don't believe that they're intentionally pushing in this way to harm the industry and the community but I do believe that , while in the midst of chasing the latest trendy object, they won't realize that they're giving up very valuable stuff that benefited the industry for a long time.
You are already doing that in a normal template. Let us say you are building a shopping cart.
The template will contain logic like an iteration over what has currently been put in the basket. And maybe some condition that if the basket is empty you should show a friendly string instead. Then you have some additional logic in a js file that will collapse the list of items if the user does not want to see everything. This is usually done by using a id/class or html element to grab on to.
The idea behind React is that you put all possible states and ways the view can render in a component. You still would (generally) not have actual logic in it; like grabbing data from the server or calculating stuff.
It is different yes but I think it is a neat idea. We will have to see if it is a viable path forward but I think this "rethinking best practices" is really good and has already influenced the rest of the frameworks quite a lot.
The main difference is that the logic in template files is the guest here while the markup is the host. We're used to include presentation info in <style> tags and code in <script> tags. So, it is not really a great deal of change to include template language within our content even though I still prefer logic-less or minimal logic template languages over full blown ones to avoid turning web pages into a whole mess.
But the problem with React is they are not being honest with marketing their technology. They claim that their approach to blending everything together as "separation of concerns " and some of their evangelists had even the nerve to claim that their approach is the only true way to best practices and that we have been doing it wrong all this time. So, it turned from product evangelism to pure propaganda for them.
If they were forthcoming about it from the get go "Hey guys, we know that violates SoC but you guys we'll make up in terms of productivity gains and speed what you will give up in maintenance and readability" but instead they keep pushing their propaganda and people seem to eat it up.
It is still mixing presentation with logic if you use a template file. So why do you think it is alright to violate SoC in that case?
They have been very detailed with what you get with React and their first presentation was even called "Rethinking best practices".
It does not violate separation of concerns. For me it is the opposite and you actually have real separation of concerns instead of separation of technologies. And even if my project is pretty young it feels like it will be easier to maintain.
How often don't you have DOM manipulation (hiding or showing a div) in the same Javascript file as some actual logic. How is that separated concerns?
It is still mixing presentation with logic if you use a template file. So why do you think it is alright to violate SoC in that case?
I am not puritan or dogmatic. That's what I have been trying to convey here. I'm pragmatic to the core but I am no propagandist.
If I was asked if template languages violate SoC, I would not hesitate to reply "SURE" but I'm keeping to a minimum and I'm using logic-less flavors instead.
But reinterpreting SoC as SoT and trying to evade admitting that you guys at fault is not really something to commend you on. Too much revisionism and propaganda for my taste.
I think you're reading too much into it. I see it as a new way of working with new tools that Facebook has found to be better for them. We can try the new tools and see if it works better for us.
Accessibility, SEO and bookmarkable resources aren't always a requirement. The GMail app (as opposed to the login page) for example doesn't need SEO. If you're targeting a known specific audience then you don't necessarily have to focus on accessibility. Bookmarkable resourecs doesn't always make sense either, for example if you're making a web based image editor (although I suppose you could create bookmarks into each images editing history or something if you're doing non-destructive editing) . Maintainability is of course important, but I've yet to see a convincing argument that one approach gives a priori better maintainability.
As a low vision computer user that supports disabled people on the web, and whose father spent 30 years working with disabled people, I can tell you for a fact that for some people, accessibility should be a requirement all the time.
Especially as more things go toward the web.
The disabled is a club anyone here can join, at any time.
Using the GP's example, it would take a huge amount of effort to make an online image editor accessible to the blind. I'm not sure that would be time well spent.
All the GP is saying is that the trade-offs will depend on your audience.
Building and application doesn't automatically mean discarding accessibility, SEO or sane URLs. Modern JS-frameworks like React handle them quite easily.
The reason I usually prefer to separate script and markup is that it makes the logic easier to test and those tests less brittle when the markup changes. Not having had any experience with react, I was wondering what the accepted approach to testing is?
One common way is to have React render into a simulated DOM (e.g. https://github.com/tmpvar/jsdom) and then trigger event handlers with code. You make assertions over the structure of the rendered DOM to know whether things went fine, all without a browser attached.
A dumber way that works remarkably OK too for simpler scenarios is to just have React render stuff to HTML strings and do regexes over those strings. Hacky, and if you're doing serious app development you probably don't want this, but it's a very easy way to get started.
This is a great question. The little iOS development that I've done it seems like the script and style are tied together with the markup.
I think about how painful it would be adding a custom button(new behavior) to a notification on a website: you either add an event listener to the dom and listen for it to bubble or add it to the button directly(the easier option). These new web frameworks seem to be adding it directly to the dom node -- we're back to <a onClick="function('value')"> which is faster, but traditionally harder to manage. But since everything is a structured component (all of these things implement an interface) we can build them faster and worry about it on the component level and not the markup level.
I've been playing with React and Riot and it is a very interesting approach. You can build things out a lot faster than you used to and that is what matters in the end. The user will not care if you separate concerns (as long as the page renders and is accessible, but that is another story).
Not familiar with react and barely JavaScript, but why is <a onClick="function('value')"> bad? I mean as longs as the function calls a function on another module and doesn't contain any more logic than that. The other module remains testable, and the only logic in the UI is a function call.
If the interface of the module changes, sure the UI would have to change, but I tend to think people over think things at this point (my opinion and I hope it doesn't distract from my original question).
As far as I'm concerned <a onClick="function('value')"> was bad because 'function' was a global variable reference.
I don't think that's the case for React though so I'm not sure if the GP saw some other drawbacks in it (apart from the aesthetic of separating logic from presentation.)
In React, you would do <a onClick={this.props.foo('value')}> (for example) - JSX would interpolate that and set up the appropriate click binding, and the function is local to the component.
My experience with iOS development is that you just have to hack things together in whatever way works. Frequently you'll get a screen 70% of the way there with slick but inflexible visual editor, then need to copy and paste a bunch of imperative methods to modify things further at runtime. All of this separation of concerns stuff is a bit lofty for iOS.
Just because your HTML, JS and CSS are in different files doesn't change the fact that they are tightly coupled. React dispenses with this superficial separation and groups presentation, behavior and styling of the same UI element together. I've found it much easier to reason about.
There is no reason that components can't share code. It's just JavaScript. Extract common code into libraries, mixins or even components.
For example, we frequently create generic containers that modify the behavior of the child or parent. One example is a container that automatically sets its children to be "sticky" once you scroll past it. Another common parent is one that renders it's children is a modal (lightbox, dialog or similar). Another is a child component that, if you nest it into another, can notify the parent whenever its dimensions change.
It's not inheritance at all. The code sharing is across interface boundaries, not like inheritance where, say, changing a member variable can break descendant classes. Instantiating a component is just like declaring a variable.
> getting rid of inheritance altogether and settling for this interface boundary sharing
You claim it is "settling" but I'll try to explain why its not only not "settling" but actually encouraging best practices. I'm not sure what language you're most familiar with but since you're talking about inheritance I'll try to provide Java analogies.
Hierarchal components => Hierarchical composition of classes
Mixins => Interfaces with default implementations (possible as of Java 8)
Inheritance, as defined by the OO paradigm, is very rarely the correct solution. Even in a language like Java, when it comes to classes, the best practice is to use composition over inheritance. If you haven't heard this before, or you don't agree, sorry but I'd rather not get into this myself. There are a ton of really good resources online about this, they will do a far better job explaining than I would.
I aint no traditionalist or a Java supremacist :). I'm just an ordinary guy with passion for anything web development and I happen to like javascript a lot.
So, I'm okay with non classical inheritance or any other non conventional constructs that would make our lives easier but I'm really skeptical about the direction that these frameworks is taking the industry as a whole in, and I believe that their lack of enthusiasm for established best practices and breaking the rules without offering well thought and coherent alternatives is worrisome.
React isn't about breaking rules or disregarding best practices. It's simply recognizing that other principles need to be applied for a certain type of application.
Those principles are in fact old, and originate in the desktop app. Every single desktop UI framework throughout history, from Xerox Star to Visual Basic to Swing to Delphi to Cocoa, has modeled the UI in terms of components (sometimes called controls or widgets) that can be contained within each other. Components are logically independent containers whose behaviour and rendering follow them around; drop a button onto a form, for example, and you get "button behaviour" without having to implement anything yourself. React follows this exact pattern.
The reason people are interested in "breaking" rules such as separation of style and markup is because those principles don't apply well to this way of doing things. Components aren't document markup to be styled, they're views that need to draw themselves. You can devise various ways to continue using CSS to "skin" these components, but this is ultimately the enemy of a good component. It turns out that for components to be true containers, they have to have complete control over their own rendering, and inserting global CSS that cascades into a component tends to violate that boundary. In other words, the component _is_ presentation, and therefore a "separation" makes no sense because there isn't much to separate.
You can debate the merit of modern single-page apps, but people are building them, and need the tools to do so. At the same time it's clear that people (not just developers) want both the power of the web, and the power of desktop apps, and developers are now trying to discover how this hybridization — the appification of the web browser and the webification of the desktop — can be attained. React is probably just one step in the search for some better converging structure.
You criticize React a lot in this thread, but I can assure that it's well thought and coherent. I've been a web developer for about 20 years, and this is the most productive and content I have been about working in a browser. I recommend trying it out.
One of the best rebuttals I have read on this thread. I'm no React hater and I honestly consider trying it out just to see what's all the buzz about but it won't still fit my definition of proper SoC.
'We' never really came to an agreement on that question. Some people always thought it was a pretty good idea to keep things that belong together close together and some people didn't. The separation people have been dominant for a couple of years, but a bunch of people didn't really like that approach and are now taking a new stab at finding a new solution the problem.
It's just two different schools of thought and really comes down to personal preference. Fashion ebbs and flows and what was old is new, and what was new is old.
In addition to what skrebbel said, let me clarify that React doesn't encourage you to mix _all_ logic with presentation, only that logic which relates to presentation; everything else ("business logic") belongs elsewhere.
The core idea is that presentation logic belongs with the presentation; you cannot separate the two. In classical MVC frameworks such as Cocoa, this is accomplished with a controller that is tightly coupled with its view. Most people use Interface Builder and maintain the view in a separate file, but this is purely a pragmatic design allowing IB to use a different file format from your code. You could write the entire UI in Objective-C/Swift code, right in the controller, and in terms of layering there would not be a lick of difference.
React, like other MVC-bases systems, encourage the UI logic to be slim and strictly UI-oriented, and to move the application logic -- that which deals with the flow of data/state -- to a separate layer.
In my opinion it is a misconception that React "mixes" representation and logic.
You can _implement_ both representation and logic with React. (instead of JS for logic, and some clunky template language for representation).
This does not mean that you should mix it. usually you end up with "representation" components that are "dumb", and logic components, that do not care about the representation of their children.
Just because it shares the implementation mechanism, it does not mean that they are mixed together. You can of course, but most of the time, you should not.
Keep in mind that the notion of separation of concerns (markup, style, behaviour) mostly refers to the end result, the rendered page. Performance is a good reason for doing this.
In other words, use css classes to style similarly looking elements instead of defining the styles inline (style attribute). Or use event delegation instead of adding a bunch of onClick attributes on your elements.
When talking about developer productivity (ie. maintenance, new feature development) what's more important than separation of technologies is separation of concerns at the "component" level.
Component in this context can be simply defined as a single file that contains all the logic required to render and manipulate a single DOM element throughout its lifecycle.
What React does (as is Angular to a lesser extend) is allow you to mix markup and behaviour while developing but keep those things separate when generating the end result.
I do undestand where you come from there, but I'd view this as a bit different.
React's building block is the 'component' – the idea being that this is an isolated part of the application. By its very nature, isolating a component means separating the HTML from all the other HTML, and the script from all the other script.
Since components are generally quite small, it makes sense to bundle these together. You don't suffer the problems that encouraged people to separate concerns in the first place (things like have loads of interacting code that's duplicated and closely tied to structure), so it's OK to take a different approach – and I must say, in practice it works really well.
CSS is a separate issue – React doesn't mix CSS into the pot at all.
> CSS is a separate issue – React doesn't mix CSS into the pot at all.
Not quite true, ReactNative does, React supports it[0] and one of the lead devs (vjeux, gave the reactjs conf 2015 keynote) has a presentation on doing exactly that[1] alongside being the lead dev on Facebook's css-layout (which IIRC underlies ReactNative's layouting)
> I'm wondering how the marrying of presentation and logic affects that.
Depends on the exact component. For pure components as part of bigger applications it's really quite easy, just render the component with a known dataset and see if it's got everything where things should be. Then again, that's similar to testing templates… most people don't really test their templates.
For self-contained "widget" components things are a bit harder, it's similar to testing DOM-based widgets really.
The idea was approximately that html was the data and css was the presentation. In reality they are quite connected and you have to write the html to support how it will be presented, a change to the presentation often requires a change to the data (html), and this doesn't really make sense.
I think a saner approach is to start with plain old data (e.g. some JSON) and have a function that can turn that into html/css/js. This is what react allows by using props/state as the input to the component/rendering function. It also permits you to pass complex objects as props/state but I like keeping to simple data as much as possible.
Changing the presentation often involves more than changing the CSS alone. For example, you might have a table of data that you want to change into a bootstrap .row/.col structure. The data itself has not changed, only the presentation, and this required a change of HTML.
The CSS always needs enough hooks in the HTML to do it's work, without the right hooks some things are impossible with CSS alone (or would be unnecessarily obscure/tricky/brittle).
HTML isn't a general data format in the way JSON is.
Basically, the paradigm has you make small components with the JS, HTML (actually XML) together, and optionally the CSS too. The reason why this works is because the HTML and JS work together to make up the structure of your component, so there's not really much of a reason to separate them. And if your component is nice and small, there's only a small amount of HTML to worry about.
The idea is to think of your HTML as a part of your app, rather than just "something that is modified by the JS".
I wouldn't say I was "forced" to use JSX. I started out building React using only JavaScript notation to build the DOM (React.DOM.div, et al.) because I told myself that XML formatted text doesn't belong in my JavaScript. I then started to use JSX. It's a beautiful thing to get into if you give it more than a cursory glance. For one, readability is incredibly better with JSX and passing data becomes less of a chore.
In my humble opinion it makes sense. At least in this direction, when (seemingly) JS code is generating the presentation layer (HTML in this special case).
In contrast to Angular where we're told to put logic in templates (or just HTML files) it looks a lot better.
Absolutely, React is in the wrong here and its methodology is a clear and direct violation of the "separation of concerns" principle.
First, they came for the HTML markup and said "come on guys, JSX is just some XML on steroids. You should not worry at all" and we didn't speak up.
Then they came for CSS and said "come on guys, they're just small components and the same as placing the CSS declarations via the style attribute anyway blah blah blah" and we didn't speak up.
So you don't really know what's gonna be their next victim. There's a lot of revisionism and reinterpretation of best practices going on in the industry and hipsters and fanbois seem to go chasing the latest shiny and trendy object out there.
Nothing we can do to help save these people!
But seriously guys, have you seen any React dev code with all those CSS declarations and HTML markup over each other?
I pity the ones who will be assigned maintain this spaghetti code.
I've actually never found myself more productive than with React, by a long shot. The reasons why mixing them together makes sense are above us in the thread, but I'd highly recommend vjeux's presentation on CSS in JS:
vjeux's presentation only applies to a very specific use case at his org namely FB. I should not imitate him just because of the fact that it fitted or served FB right. We should think on our own and figure what works for us and not blindly follow FB's or any other org's lead.
Re productivity, if it works for you, good for you but please don't attempt to reinterpret/bend the rules that are well established in the industry just to avoid criticism. For me, it's just an act of intellectual dishonesty.
React does violate the principle of separation of concerns and "we're working on a component not a document level" is not fooling anyone.
We should alert and educate people on this issue and then they can decide for themselves if they would go ahead nevertheless or stick to their guns. That's all!
I am curious, what concerns are not being separated? You have presentation markup with presentation logic. Actually it seems to me the concerns are being brought closer together.
Or are you making artificial boundaries between declarative and imperative code?
I'm OK with presentational markup co-existing with logic but to be honest I prefer it the template way not the other way around where the markup is the guest at the JS file.
But throwing CSS declarations to the mix is just too much for me. Now I'll have to maintain markup/presentation/logic in the same place, that's a nightmare and ticking bomb IMHO.
>Now I'll have to maintain markup/presentation/logic in the same place
Only if you're doing it wrong. Presentation logic and markup will be in the same place sure, that's a good thing, but any application logic not dealing directly with displaying dom elements shouldn't be in and among your presentation code. Your concerns are separated and your presentation code is in the same place, like you would logically think they should be.
I have watched React Native talks in which they were advocating for this and bluntly calling it proper "separation of concerns".
But when you say that presentational markup and logic should be grouped together, doesn't this mean that we have to divide our js files even further to separate business logic from presentation or view logic?
Fair enough but please don't go around telling that mixing content/presentation/logic in a single entity is a valid case of "separation of concerns" but on a micro and not macro level. That's just not right!
>We should think on our own and figure what works for us and not blindly follow
But doesn't your last comment rail against all these "fanbois" not blindly following "best practices" and actually attempting to find out what works best?
In fact, your next sentence in this comment:
>please don't attempt to reinterpret/bend the rules that are well established in the industry
Thanks for the guide. Looks awesome! I've recently started working on a SPA in React and was desperately googling around information. Glad to see it in one document.
BTW - I can see that the section on Flux and Alt is still left to be written. Any idea when you'll have the drafts for those sections ready? Lastly, it would be nice if you could contrast Alt with Reflux and give us your recommendations on what to work with.
At the rate I am going, I am hoping by next week. But, the author of Alt has already written an amazing getting started guide: http://goatslacker.github.io/alt/guide/ - check it out!
As for a contrast between Alt/Reflux, I am hoping others using different Flux libraries will contribute and share their views, I will also link to some comparisons others have already done, such as: http://pixelhunter.me/post/110248593059/flux-solutions-compa.... But if I have time to, I'll give it a try!
It's not really that SPA specific, if you want to just use React for the View, then Part 1 and Part 4 (to be written) is probably all you need to get started.
Collectively, all the parts of the primer, together should give you the tools you need if you want to build a SPA.
What are your thoughts on, and how do you let your clients know (since you're a web agency?), that using anything built by Facebook comes with a huge business risk?
With the included PATENTS file, if Facebook decides a patent they filed is something you violate then they will sue you or ask for a royalty. If you try to fight it or even suggest it's not valid then your license for React and all other Facebook projects becomes voided. This gives incredible leverage and power to Facebook for anyone developing their core business with anything they've made/open sourced.
EDIT: https://github.com/Raynos/mercury was suggested as an alternative, I'm not sure how viable it is for different types of projects.
Using code written by Facebook is not a huge business risk, unless you consider the use of any open-source code to be a business risk.
The PATENTS file that Facebook distributes with it's open-source projects grants additional guaranteed rights. It does not place any additional restrictions or risks on your use of the software, above and beyond any that exist with other licenses that do not grant patent rights.
If you "try to fight it or even suggest it's not valid" then you do not lose your license for react and all other Facebook projects – what you lose is the additional patent rights grant. That's a huge difference!
"Facebook is granting you additional rights on top of the BSD license. In the worst case, where you do something that causes the patent rights to be revoked, you're still left with the same rights you have under the BSD license. This is unambiguously safer to use than if they had released it under a vanilla BSD license. As for why Facebook did this, they're most likely trying to give away additional rights while still maintaining the ability to use these patents defensively, in the event someone sues them for infringing a different patent."
This is 100% totally and completely wrong :)
The BSD license normally includes an implied patent license.
It says " Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met .. "
This grants an implied patent license to the patents necessary to actually do this, as long as you meet the restrictions.
This is actually well settled law. You don't get to give people stuff unrestricted, and say "you can use this for free", and then say "just kidding, what i meant was, you can use this for free as long as you pay me for the patents"
However, when you do what facebook has done, and give an explicit license, you have overwritten the terms of that implied license, and you get no implied license.
So it is not only "not unambiguously safer", you are not "left with the same rights you had under the bsd license if it is revoked".
This is because if you revoke the explicit grant, you get nothing in terms of patents. But the implicit grant is not revokable unless you violate the copyright license.
So sorry, but this is not "better than the default" and does not in fact, help you.
It's undue paranoia. It says essentially the same thing as the Apache 'Grant of Patent License' section. Namely, if you instigate a patent lawsuit, the free patent license offered by Facebook no longer applies. It would be impossible for Facebook or Apache to engage in patent lawsuits if they did not include this termination clause.
Besides, Facebook is gonna sue you if you violate their patents, regardless of whether you use React or not. And the termination pertains to the patent license. They can't restrict your access to a BSD licensed software package.
This isn't accurate according to what DannyBee says, an open source lawyer - please read my comment above at https://news.ycombinator.com/item?id=9256093 that includes copy/paste of a comment he's made before.
TL;DR: Facebook is changing the BSD license from being an implied license to being an explicit license, so it's not the same as BSD license.
* If Facebook is "changing" the BSD license, why is the BSD license included verbatim and in full?
* Also, why does the PATENTS file explicitly state that it is an "ADDITIONAL grant of patent rights"?
* Why don't I see comments like the one I originally replied to being posted on articles pertaining to Apache? They have almost exactly the same wording in their statement.
I'll believe claims of Facebook "changing the BSD license" when they actually change the BSD license.
It's easier to piggyback on something, for practicality reasons, and perhaps to piggyback on the perception people have of it (maliciously or not).
ADDITIONAL could simply mean added to, not necessarily extra or supplementary - added, as in, included with - an overlay of BSD.
I agree, it'd be good if Facebook was more transparent as to what it all means. Stating that you'll believe it if they modify the actual BSD license, it's far more easy to take an existing - and generally accepted license - and then make an addition instead of making changes to it, no? So you don't have to call it something other than BSD?
No, this is not correct. Please stop spreading this misinformation.
Your license to use React is not contingent on 'not to sue them' – however, the additional patent grant that they give you is contingent on this. This patent grant is in addition to your license to use the software.
If you accuse Facebook of violating one of your patents, then you automatically lose the right to use any of theirs. You do not lose your license to use the software, which is a totally orthogonal issue.
Facebook is changing the BSD license from being an implied license to being an explicit license, so it's not the same as BSD license; via DannyBee (open source lawyer), https://news.ycombinator.com/item?id=9113505
I think it's worth mentioning that software copyright licenses (like BSD) cover a particular implementation (a.k.a. "creative work") while U.S. patent licenses cover a design.
The likely reason for Facebook including the explicit patent license is that with an implicit license it is unclear if derivative works also share the rights to the granted patents (e.g. "can I take part of the implementation that utilizes a patented design and use it in another project?") [1].
The implicit patent rights of the BSD license may or may not extend to derivative works or different distributors, but the Facebook PATENTS file clarifies that it does not and avoids the ambiguity. For places outside of the U.S., that do not care about U.S. patent law, but do respect copyright, the BSD license is still in effect.
I don't think that simply using Facebook software will open up your business to a "huge business risk" -- any more so than you'd be doing by working on the assumption of an implied patent right grant on the derivative works permitted by the BSD license. IANAL.
It may not be correct, but do you deny that it's already been repeated enough that it'll take another 6-12 months of wasted hallway conversations discrediting it?
When that BillG email for money urban legend first came out relatives literally called just to ask about it.
IANAL however it's more correct than people realize. Facebook is changing the BSD license from being an implied license to being an explicit license, so it's not the same as BSD license via DannyBee (open source lawyer), https://news.ycombinator.com/item?id=9113505
Question from a JS layman: React is great in comparison to what? vanilla JS? Angular/Backbone/Ember? JQuery? any other *.JS?
Also is this a good direction for "mobile first" approach? What about platform independence? (iOS/Android/Desktop agnostic, etc, etc). (bootstrap? phonegap?)
In comparison to Angular, React is more idiomatic. It is very easy to reason about the scope, lifecycle, and performance of React components if you are familiar with JavaScript as a language.
In comparison with Backbone/JQuery, React is more declarative. It encourages the developer to describe the structure of the UI in a given state and let the engine handle the transitions between states. It's possible to use Backbone models and events with React views with very little impedance mismatch.
I would like to hear an Ember expert's perspective.
React Native has an interesting approach to mobile-first development. The general philosophy is "learn once, write anywhere" instead of "write once, run anywhere". Most apps cannot make the most of their platform while being truly platform-independent, but unifying component lifecycle behavior between platforms could end up being easier on developers than learning the particulars of each platform, while producing a better result than a PhoneGap-style wrapper.
I'm not an expert ... I dabbled a bit in Angular and found it really confusing and hard to debug. React worked mostly as expected. There were some gotchas but I managed to get through them in a few days.
I just wish we had a non-proliferation treaty on Flux frameworks.
Flux is an idea, there's multiple implementations because they optimize for different concerns.
For example, I like Fluxible because it lets you do server side rendering, and it avoids singletons, so it's exceptionally easy to test.
However, if I'm working on an app that doesn't have any public facing components, I'd probably consider a different implementation that is less verbose.
The proliferation of Flux frameworks will probably continue for a while. Then, hopefully, things will settle down and we will only have a few frameworks left that have clear differences which makes it easy to choose between them.
I currently like Reflux and would choose that as a start if I created a new project.
For me React is great in comparison to anything I've tried before, which was really hand-rolled, jQuery, and Backbone. I tried to get into Ember/Angular in the past, but the learning curve was way too high. I didn't have time to spend a month going slow. With React, I was up and running within a day.
Of course, it took way longer to put together a good stack. I spent months pushing React and trying to learn the best practices there.
I did end up with something relevant though. I built Reapp: http://reapp.io
It's really a bunch of things in one, but I think it's hugely overlooked for being an awesome bootstrapping method for getting a full-featured React app up and running. You can have your app running with hot reloads, ES6, cordova-builds, flux, etc all in minutes with a single command. And of course it includes an awesome (IMO) UI kit to boot.
it's funny how for years i heard how bad CFML was because of mixing in logic and presentation in custom tags. now for some reason react makes this cool. we've come full circle.
Hey by the way, the slack channel, Reactiflux, is actually pretty strong, check it out. Many people there are actually using React on large scale apps, myself included, and there is plenty of discussion.
The "URL router" in my current project begins with "onhashchange = function () {" and is essentially a five line conditional. It might grow to ten lines. All it does is set the root props based on query parameters. Not rocket science. I'm using Fetch.js and a Promise polyfill in order to do AJAX stuff (the native XHR API is a bit tedious).
But basically the answer is: yes, you can! You can even write an SPA using nothing but the regular W3C APIs! React just makes it very easy to keep the DOM in sync with your application state.
I had to write my own router, but the event system [1] allows you to catch left-clicks or touch events and let you decide how to handle them and the lifecycle functions [2] allow you to update history/URL params to reflect the state of your app. If you have app state which isn't easily serializeable, then you'd have difficulty providing a good URL structure for people but you'd probably have that issue even if you weren't using react.
Sure. You may not want to depending how big and complex the application is, but it's definitely possible.
A router and an immutable collections library (immutablejs or mori for instance) are very convenient additions, but by no means necessary. Hell you don't need a precompilation phase either by skipping JSX (and unsupported ES6 constructs).
Yes. I have built a few. The router I chose was Flatiron director (link: https://github.com/flatiron/director ). I used jQuery for Ajax calls. Everything else was React + Flux.
lol everytime something about React or Flux gets posted on HN, we get this massive comment thread debating how X React feature isn't best practices (Inline styles, full-app re-render, singleton dispatcher or whatever).
Get over it nerds. React is very well thought out, and Just Works™. Your me-too diatribe about how being different is bad doesn't help anything but feed these endless debates. Build apps or die. If you prefer building lousy implicit Rails apps, go wild.
There's a tutorial bubble for these frameworks and languages. Too little to say, too much reexplanation of the basics. You end up reading for days and knowing less than what you would know if you started playing with the tools.
One problem is that angular 1.x is considerably more complicated than react. There's John Papa's style guide [0], but IMO it's not great.
There's an angular review [1] that I believe hits the nail on the head:
"Angular wants you to build your application in a particular way, but it’s not very explicit about it. Call it “passive-aggressive architecture.”"
After using angular for over ~2 years, I'm far happier with react (and a flux implementation, if doing something more complicated). You end up with far simpler code and more maintainable code.
The fact that the angular team itself is doing a complete rewrite that throws away almost all the fundamentals of angular 1.x shows a clear recognition of the many flaws present in it.
As esro360 said, goods router (like react-router) will keep your ability to open site links in different tabs, as well as keeping your location (and history) in sync with different views. Things have evolved since the first SPAs.