Home » Tutorials » JavaScript » React For Absolute Beginners – Part 3

React For Absolute Beginners – Part 3

React For Absolute Beginners – Part 3

The Full Series

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.

<script>
function alertFunc() { 
    alert('Hello World!');
}
</script>

Second, register a mouse onClick event to your JSX element.

<script>
<img onClick={alertFunc} />
</script>
* please be noted that  in HTML, event listener names are written in all lowercase, such as onclick or onmouseover, but in JSX, event listener names are written in camelCase, such as onClick or onMouseOver.

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">Hey</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>
*Important: please be noted that you can’t inject If/Else into JSX expression. The things will break!

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

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!


Android, iOS Development Tutorials