The Full Series
- Part 1: Getting Started with JSX
- Part 2: Rendering JSX Expression
- Part 3: Advanced React Knowledge
- Part 4: Writing Your First React Component
- Part 5: More to come…
You’ve learned to understand what is ReactDom and its render method to render JSX expression on screen on the “React for Absolute Beginners – Part 2, Rendering JSX Expression. Now it’s the time to learn some of the advanced JSX knowledge before you make your first React Component!
Event Listener
JSX elements is just like HTML elements, you can attach an event listener to it. Here’s an example:
First, create a valid function.
function alertFunc() {
alert('Hello World!');
}
Second, register a mouse onClick event to your JSX element.
<img onClick={alertFunc} />
JSX Element’s ClassName
In JSX, you can’t use the word “class” when defining class to your JSX element. You’ve to use “className” instead. This is because JSX gets translated into JavaScript, and class is a reserved word in JavaScript.
<h1 className="big">Hello</h1>
Curly Braces
Always wrapping your JavaScript code in curly braces, because any code in between the tags of a JSX element will be read as JSX expression, which means it reads them as text, not as regular JavaScript. Example:
<h1>3 + 3</h1>
will output as:
<h1>3 + 3</h1>
If you wrap your code in curly braces, the code will add up the calculation for you:
<h1>{ 3 + 3 }</h1>
will output as:
<h1>6</h1>
Example:
<h1>
{
if (signIn == true) {
'Welcome Back!'
}
}
</h1>
That is the rule when you writing your JSX expression. So the option is to write the IF/Else statement outside the JSX expression, here’s example:
let message;
if (signIn == true) {
message = (
<h1>
Welcome Back!
</h1>
);
} else {
message = (
<h1>
Please Sign In!
</h1>
);
}
Use Variable in JSX
You also can use access to any variables that declares outside JSX expression, for example:
const title = 'My Friend';
const h1 = <h1>Hello { title } !</h1>
// will output as <h1>Hello My Friend !</h1>
Hooray! You’ve learned some of the advanced JSX knowledge & common errors to avoid when you’re writing your first React Component later. ^^
In the next chapter, you’ll learn how to make your first React Component!