4.1: JSX Overview
Before we talk about class components, it's extremely important that we discuss JSX. It might surprise you to know that we have barely written any HTML at this point. In fact, the only HTML in our app is in the index.html
. The rest is called 'JSX', which stands for JavaScript XML.
Let's start by looking at a translated snippet of JSX code.
Copy the following code.
Go to the website
babeljs.io
.Click 'Try it out' in the navbar.
Paste the code in the left box.
After pasting it, you'll notice, that on the right side, you'll see an enormous chunk of code:
It's not necessary that you understand all of the above code right now. What is important is that you recognize what's going on under the hood with all of this code that appears to be HTML. It's actually just JavaScript in the whole file. React has made it so that we can write in what appears to be HTML. Think of the implications here: we can write JS functions and HTML in the same file in an extremely fluid way. CSS can go in there, too, but we'll get to that later.
As a React developer, you still have to know HTML5, and you have to know how to write it, since JSX highly resembles HTML5. You might think that this could be a shortcut to learning vanilla JavaScript. Quite the contrary, in fact, the more vanilla JavaScript that you know, the better you'll be with React. React works in tandem with JavaScript.
JSX Gotcha - Use className
While most of JSX highly resembles HTML5 and many of the tags are exactly the same, there are some gotchas. There is a big gotcha difference that you might have already noticed:
RULE: className
is used in instead of class
.
Why is this? In ES6, JavaScript introduced classes. This means that class
is a keyword in JavaScript, and it has an entirely different meaning. We'll actually study that next. Hence, since JSX is actually JavaScript and since class
is a keyword in JavaScript, React uses className
.
Even though you might read this, you will still get hit by naming it wrong from the habit of using class
, just be aware of this one.
Review Challenge
Here's a quick challenge for review:
In your
concepts
folder, add a component called called 'JSXRules'.Use the dl, dt, dd, and tags to make a table with the following notes about JSX.
Resembles HTML - It's not HTML. Closer to JS.
React.createElement() - Used to construct and update the DOM.
Not required - Developers don't have to use JSX.
Use an Arrow Function to create the component. (Already done)
Make your component navigable from the sidebar.
Last updated