JSX, HTML-in-JS and CSS-in-JS

Lately, I’ve been hearing a lot of people talk about JSX as if it is HTML-in-JS. So let me clear something up:

JSX is not HTML-in-JS.

The thing about JSX is that it is just a special syntax for writing plain-old JavaScript.

Each JSX element compiles to a call to a JavaScript function called React.createElement. In fact, you can write apps without using JSX at all; just call React.createElement by itself. Like this:

ReactDOM.render(
  React.createElement('div', {}, "Hello, world!"),
  document.getElementById('app')
)

To repeat myself, JSX is not HTML-in-JS. Yes, it is a way to specify the structure of the DOM. But so is raw JavaScript, like this:

const app = document.getElementById('app')
const hello = document.createElement('div')
hello.appendChild(document.createTextNode('Hello, world!'))
app.appendChild(hello)

If you’re writing an app with JavaScript, you need some way to modify the DOM. JSX is one way of doing it. Raw JavaScript is another. But in either case, you’re still working with JavaScript.

In contrast, HTML-in-JS would look a little like this:

const hello = "<div>Hello, world!</div>"
document.getElementById('app').innerHTML = hello

And sure, this is something you can do. Just like you could chug a bottle of Tabasco. A friend did that once. He was weird. But I digress.

Want to learn more about fundamentals like React.createElement? My Learn React By Itself series was made just for you!

CSS-in-JS

Another thing a lot of people are talking about lately is CSS-in-JS.

Unfortunately, CSS-in-JS is actually exactly what it sounds like. It is literally CSS in a JavaScript file. Let me repeat that. It is actually CSS in a JavaScript file.

The thing is, there are a number of very good reasons we generally put CSS in CSS files (or their LESS/SCSS cousins). For example:

  • Browsers expect to load CSS from CSS files.
  • Editors have syntax highlighting based on file extension.
  • Tooling such as minifiers and linters expect CSS.
  • Existing CSS libraries are written in CSS, LESS or SCSS.
  • CSS files can be cached separately from JS files.

Some CSS-in-JS tools do lots of very clever things to provide workarounds for all of these issues. But if you just use CSS or LESS or SCSS, you don’t need to provide workarounds. It just works.

Of course, there are supposedly a number of benefits. But most of these benefits can be had from more mature tooling like LESS, SCSS, CSS Modules and Webpack (which you’ll need anyway to, you know, put your CSS back into CSS files).

There are some benefits that are unique to CSS-in-JS:

  • You can add things like media queries directly to components, whilst you can’t with standard inline styles. (Yay?)
  • You can share JavaScript variables with stylesheets. Except that this is is massive security hazard.

But all the big names are using it, so it has to be good, right?

So here’s the thing: CSS isn’t perfect. It makes sense that smart people are building alternatives. And the tools do have some compelling use cases — they’ll work with react-native, for instance. But unless you 100% know what you’re getting into, and 100% understand the security implications, I’d wait a little bit longer before jumping on any bandwagons.

I’ve put a few more details on React Armory in my answer to Should I use CSS-in-JS?.

More good news

Keeping up with JavaScript and React can be exhausting — but it doesn’t have to be! The secret is that the basics never change. In fact, my most popular articles are ones I wrote years ago, and they’re still as relevant as ever.

JavaScript fatigue happens, but you can avoid it by sticking to the basics. And that’s why my fortnightly newsletter just focuses on the JavaScript and React fundamentals. So subscribe now — and get a bunch of free PDF cheatsheets as a bonus.

I will send you useful articles, cheatsheets and code.

I won't send you useless inbox filler. No spam, ever.
Unsubscribe at any time.

One more thing – I love hearing your questions, offers and opinions. If you have something to say, leave a comment or send me an e-mail at james@jamesknelson.com. I’m looking forward to hearing from you!

Read more at React Armory

Announcing React Armory

You may have noticed that the updates having been coming a little slower than usual lately. And now I can let you in on the reason!

I’ve been working on a new set of React guides, but with a catch: the code examples on React Armory are live! This means that you can learn React without leaving your browser. In fact, now you can learn React without even leaving your tab.

I’ll be steadily adding more guides over the coming months. But to start out with, I’ve put together a new version of my “Learn Raw React” guide, which starts with Introducing React.

React Armory also includes a number of live examples, where you can test new ideas without configuring anything. For an example, you can play with this Animated Fractal Tree.

As always, I’d love to hear your feedback! Perhaps something in the new guides is unclear? Or maybe there is something you’d like to read about more? Whatever the reason, you’re always free to send me an e-mail at james@jamesknelson.com. I’m looking forward to hearing from you!

Introducing MDXC: A new way to write Markdown for React

Read the README and browse the source on GitHub, or mess around with the live demo.

Markdown is a fantastic tool. It makes writing simple. Markdown documents are plain text, so you don’t need to worry about tags and HTML and all that. You just write. And when you need a <a>, or a <h1>, it’s already there. It’s like magic!

But say you’re writing a React app with pushState, and you don’t want your links to use <a> tags; they break your smooth navigation. You want them to use react-router or react-junctions’ <Link> tags instead. And you’re shit outta luck, because you can’t. Or you couldn’t, before MDXC.

MDXC is a tool to make Markdown and React best buddies. Unlike traditional Markdown, MDXC produces actual JavaScript — not strings of HTML. MDXC lets you embed raw JSX within your Markdown, and even lets you import components and accept props. And to top it all off, MDXC lets you configure how each element is rendered, giving you all sorts of ways to confuse your users and also a few ways to genuinely improve their experience.

If you can’t tell yet, I’m pretty excited about MDXC. So please indulge me and take a gander at this example:

Continue reading

The Haiku Of React Routing Principles

This is the third article in a series on junctions.js. You can read this without reading the others first. But for your convenience, here is part one and part two.

Junctions.js is a router that is based on principles. These principles ensure that Junctions works with React instead of fighting against it. They’re the reason that junctions.js lets you write idiomatic React components instead of some routing-specific dialect of React. And as it happens, they form a haiku:

Components compose

Browsers show “Back” and “Forward”

Get outta’ the way!

But haiku gimmicks aside, each of these principles can make a huge difference to how you route your application. So let’s have a look at each in turn.

Continue reading

Why I created junctions.js

TL;DR? Junctions is a new, composable alternative to react-router. Get it at the junctions.js website!

It was pretty normal day in Tokyo when I received a request from a client. “I’d like this application screen to be a React Component. And I want it to be reusable.”

Given my client’s app was created with React, I naturally said “Yes Sir”. I mean, the best part about React is that components are reusable. What could go wrong?

Continue reading

Do I Even Need A Routing Library?

So you’ve decided to build a React app. It has a few screens, so you need a router. And react-router seems pretty popular, so you npm install it and put together a quick demo. Everything seems fine and dandy!

Or it did, until you googled for some docs the next day. Something seems off. The logo has changed colour from blue to red. And the version number has mysteriously increased from 2 to 4. Huh?

Well at least it didn’t jump to 5. But this makes you think — do I really even need a routing library? Imagine if we lived in a world without JavaScript fatigue where the APIs never change and we could just focus on making awesome stuff. But actually – we kind of do! The browser APIs rarely change. And how much longer could it take to just use them instead of some complicated library?

Continue reading

The 5 Types Of React Application State

I don’t know about you, but when I started writing React apps, I struggled to decide where my state should go. No matter how I re-arranged setState calls, things never felt quite right.

"Messy state"

And maybe that is why I got so excited when I found Redux. Redux gave me a single place to put all my state. Which sounded great in theory.

"What if"

But then I realised that having one spot to put things doesn’t necessarily make them easy to get to.

"Still messy"

It turns out that I needed more than just a place to put things. I also need a system for putting them in the right place.

"Banzai!"

For me, that system came from splitting my state into five categories. It turned the problem of deciding “how does this piece of state relate to all the other state”, into the problem of deciding “what type of state is this”. And as it turns out, this is a whole lot easier.

Continue reading

Why use parenthesis on JavaScript return statements?

A while back, I received a great question from a reader:

Just a note in your Learn React By Itself tutorial. In the “Components” section, where you say:

return (
  React.createElement('li', {className: 'Contact'},
    React.createElement('h2', {className: 'Contact-name'}, this.props.name)
  )
)

It’s not clear to me why you need the parens and can’t just do return React.createElement. I tried that and it fails but I can’t see why. Isn’t typeof x === typeof (x) in JavaScript?

And while it is true that typeof x === typeof (x), the same doesn’t always hold for return. Why?

Continue reading

Lament of the keyboardist

I browsed the Truly Ergonomic
But support sounds truly lethargic

I wanted the Keyboard IO
But manufacture is too slow

I trailed the Filco Ninja
With staggered keys which may cause injure

So stuck with Kinesis Advantage
Somewhat like an unwilling hostage

As jamming shift causes excitement
And coloured keys make Colemak blighted

But faced with carpal tunnel syndrome
I’ll gladly take stockholm syndrome

State of React #2 – From Inception to Redux

Welcome back to the second instalment of State of React! In case you missed it, the first instalment demonstrated a small app without component state. And it received a bunch of interesting responses, like this one from @metapgmr:

using props as state and claiming that components are … stateless! The React Emperor has no clothes

Yes, the app was basically wearing its birthday suit. And yes, the app did contain state. But no, the state wasn’t in the props – and it wasn’t component state either.

So what was it?

Continue reading