Learn React With Me — JSX

Photo by Rich Tervet on Unsplash

If you are coming from Instagram, thank you for following my series! If you are coming from somewhere else, welcome! I’m excited to have you reading this as well. You can read the introduction post here: Learn React With Me

Today’s topic is JSX.

JSX is a syntax extension to JavaScript. Basically, it looks a lot like a template language (think, HTML) and comes with the full power of JavaScript.

Why JSX? 
React believes that rendering logic and UI logic go together. I do too! This includes anything from how events are handled to how data is displayed on the screen. Instead of separating this logic into different files, React contains both in what’s called a component. We will discuss components a little later, so keep that in the back of your mind. React doesn’t require JSX, but most people find it helpful. Honestly, as we go through learning React in this series, you will prefer using JSX. It’s nothing too tricky to wrap your head around.

An example:

const name = ‘Courtney Corlew’;
const element = <h1>Hello, {name}</h1>;
ReactDOM.render(
element,
document.getElementById('root')
);

What we are doing in the example above is setting my name to a variable called name. We are then using that variable in between the curly braces to render my name in the variable element. We are then rendering the variable element onto the DOM. That’s a simple example of what JSX looks like!

With JSX, you can put any valid JavaScript expression inside the curly braces. A lot of the time, it will be used to display data — like my name in the above example.

JSX compiles into regular JavaScript objects. This means while writing these components, you are able to use if and for statements and have it return a value. The possibilities are endless!

There are other ways to set attributes!

You can use string literals:

const element = <div tabIndex="0"></div>;

You can also use curly braces, like above:

const element = <img src={data.name}></img>;

It’s important to remember, you can use either quotes or curly braces, but not both for the same attribute.

Also, in React it is recommended to use camelCase when naming attributes, since it’s closer to JavaScript syntax than HTML.

As we talked about earlier, JSX represents objects. These objects are called React elements! React uses them to construct the DOM and keep current with the data it is presented with.

The next lesson will be rendering React elements to the DOM!

To view more about JSX, look here:

https://reactjs.org/docs/introducing-jsx.html

https://reactjs.org/docs/jsx-in-depth.html


To get notified of new lessons and other fun things, sign up for the newsletter: https://mailchi.mp/3ce9c26a2bd8/learnreactwithme