
A Primer for Building Single Page Applications with React - tilt
https://github.com/mikechau/react-primer-draft
======
unklefolk
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.

~~~
skrebbel
> _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)

~~~
NoGravitas
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?

~~~
skrebbel
> _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.

~~~
timepiece
_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.

~~~
rpedela
> 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.
[https://speakerdeck.com/vjeux/react-css-in-
js](https://speakerdeck.com/vjeux/react-css-in-js)

EDIT: I gave wrong presentation link initially.

~~~
timepiece
_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

~~~
origin-unknown
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.

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

------
mcx
Author here, the primer is still in the draft phase but feel free to share
your feedback / make pull requests!

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

Thanks a lot, again!

~~~
mcx
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/](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...](http://pixelhunter.me/post/110248593059/flux-solutions-compared-by-
example). But if I have time to, I'll give it a try!

------
loceng
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](https://github.com/Raynos/mercury)
was suggested as an alternative, I'm not sure how viable it is for different
types of projects.

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

~~~
loceng
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](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.

~~~
dada78641
This raises some questions:

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

~~~
loceng
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?

------
fizixer
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?)

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

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

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

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

~~~
ExpiredLink
Software is a fashion industry.

~~~
rip747
So does mean I can start sporting a mullet and bell-bottoms to work to code in
VB?

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

~~~
nileshtrivedi
How do I join? It seems I need to be invited by the team admin.

~~~
tilt
Request an invite from [http://reactiflux.com/](http://reactiflux.com/)

~~~
dinosaurs
Seems like the website is down. Any other way to get invited?

------
phelmig
I have been toying with reactjs a few weeks ago and this would have helped a
lot to get going. Great guide!

------
JDDunn9
Can you build an SPA using just React? At the very least it seems like you'll
need a URL router, and something like underscore.js to fill in the gaps.

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

~~~
krat0sprakhar
I, for one, would love to know more about how this is done. Is your code open-
sourced by any chance? Thanks!

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

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

~~~
chippy
I dunno, I prefer going through a basic list / hello world tutorial first, and
then experimenting.

------
bananaoomarang
Hey, this is really nice. The sort of quick-reference guide w/ examples I
wanted a couple of months ago, nice!

------
davidy123
Looks like a nice tutorial, but the very strange use of `code` markup makes it
harder to read than it should be.

~~~
mcx
Ah sorry about, I was trying to highlight keywords but I might have been too
liberal about it.

------
andrewrice
This is great. Does anyone know of a similar primer for Angular 1.*?

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

[0] [https://github.com/johnpapa/angular-
styleguide](https://github.com/johnpapa/angular-styleguide) [1]
[http://www.letscodejavascript.com/v3/blog/2015/01/angular_re...](http://www.letscodejavascript.com/v3/blog/2015/01/angular_review)

~~~
andrewrice
Thanks for the insight! :) I'm just starting to get my feet wet with JS
frameworks so the input is appreciated.

------
pixelHD
I've been looking for such a guide for react! thanks!

------
MichaelCrawford
Please don't build single page applications. They drive me bananas.

Consider how difficult it is to open different sections of your site into
separate tabs.

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

