Coding / Programming Videos

Post your favorite coding videos and share them with others!

Learn React With Me — JSX – Courtney Corlew – Medium

Source link

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>;

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={}></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:

Source link


Leave a Reply

Please Login to comment
Notify of
Translate »