githubEdit

Advanced JSX

Self-Closing Tags

Most HTML elements use two tags: an opening tag (<div>) and a closing tag (</div>). But some HTML elements don't require a closing tag like (<img>) and (<br>).

In JSX, you NEED to include the slash in the closing tag. Otherwise, it will raise an error.

Fine in JSX:
 
  <br />
 
NOT FINE AT ALL in JSX:
 
  <br>

Curly Braces

Any code in between tags of a JSX element will be read as JSX, not regular JS. JSX doesn't add numbers - it reads them as text (like HTML).

To get the program to treat it like ordinary JS, we can wrap the code in curly braces like this:

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
  <h1>{2 + 3}</h1>,
  document.getElementById('app')
);

This way, it will compute {2 + 3} and output the number "5" instead of giving you the text "2 + 3".

Variables

You can access variables while inside of a JSX expression event if those variables are declared outside:

Variable Attributes

We use variables when we want to set attributes. For example:

Object properties are also used to set attributes like this:

Event Listeners

You can create an event listener by giving a JSX element a special attribute:

An event listener attribute's name should be something like onClick/onMouseOver.

An event listener attribute's value should be a function. For example:

Note: Event listener names are all written in LOWERCASE.

Last updated