How JSX makes your life easier

My favorite way React makes components easier to build is JSX –  a JavaScript extension language that feels like you're putting HTML straight in your JavaScript.

const html = <p>This crazy fox</p>

JSX makes HTML a first-class citizen of your JavaScript code. That means you can reach right in there and get your hands dirty. You're working directly with the stuff you're building: The UI.

Like Jamie Oliver πŸ‘¨β€πŸ³ squeezing a lemon πŸ‹

Jamie Oliver juices a lemon through his hand

At first glance, JSX looks a lot like HTML. Familiar HTML syntax, all the same basic elements, etc.

But there's a twist: Your JSX compiles to pure JavaScript function calls. Something like this πŸ‘‡

const html = <p>This crazy fox</p>

// becomes

const html = React.createElement('p', {}, ['This crazy fox'])

You could write your whole React app using createElement, but I wouldn't recommend it. JSX is a great abstraction.

Just like HTML, JSX lets you add attributes to your elements. Anything you'd like. Even custom ones you make up on the spot.

We'll talk more about what happens with custom attributes in the next section about components. For now I want you to keep in mind that you can use curly braces to add any JavaScript expression anywhere in your JSX.

Check this out πŸ‘‡

You can assign some HTML to a variable called link and insert it into other HTML using curly braces. You can even put 1 + 5 + 6 in curly braces and it evaluates.

Works for attributes too πŸ‘‡

See? You can use href="https://google.com", or you can assign the URL to a variable and say href={url}. Pretty neat.

A special attribute we used was style, which takes an object mapping CSS properties to their values. style={{ ... }} might look strange, but you can think of it as shorthand for style={styleObject}. It's an easy way to style your output. We'll look at it in more detail later on.

As well as basic HTML attributes, you can assign event handler. Those take a function as their value and usually look like onEvent={function}. More on event handling later.

All this works because JSX compiles into JavaScript createElement function calls. But you'll never have to worry about that :)

What's important is that you have HTML which you can directly control with JavaScript. It really is a first-class citizen in your code.

Practice

Get a hang of it with some practice

  • add a paragraph, <p>, of text
  • give it a title with <h1>
  • make your title red
  • try getting the color of your paragraph from a constant
  • render a couple of different links
  • try making an array of link elements and rendering them in a loop

Know someone who wants to learn React and its whole ecosystem? Share πŸ‘‡


Cheers,
~Swizec