JSX

I. What is JSX?

JSX is a syntax extension to JavaScript that allows React Elements to be written inside JavaScript using HTML tags.

const element = <h1>Hello World</h1>

Without JSX, the process is much slower:

const element = React.createElement("h1", null, "Hello World!");

Before JSX can render in a web browser, it must first be compiled into regular JavaScript. We use Babel to do it.

II. JSX Elements

A basic unit of JSX is called a JSX element.

const element = <h2>Hello, world!</h2>;

III. Using JSX with JavaScript Expressions

We can embed JavaScript expressions into JSX with curly braces.

Examples

let str = "World!"

let element =  <h1> Hello {str}</h1>
let item = {
    name: "Butter",
    price: 10
}
let element = <p>{item.name} : ${item.price} </p>
let length = 20
let width = 10

function area(x,y){
    return x * y
}

let element = <div>The Area is: {area(length,width)}</div>

IV. Attributes In JSX

We can supply attribute values using a string literal surrounded by quotes:

const example = <h2 id="example">JSX Attributes</h2>;

We can also supply attributes values by embedding a JavaScript expression using curly braces:

let element = <img src={product.imageURL}></img>

However, do not surround curly braces with quotes because it will cause your expression to be treated as a string literal:

// Do not do this
let element = <img src ="{product.imageURL}"></img>

V. Note

1. className

A big difference between JSX and HTML is the way we add classes to elements.

Because class is a reserved keyword in JavaScript, we can’t use it in JSX.

We have to use className in JSX instead:

<h1 className="greeting">Hello</h1>

2. Self-closing tags

When you write a self-closing tag in JSX, you need to include a forward-slash immediately before the final angle-bracket.

<br />

VI. Using JSX with Nested Elements

React Elements can be nested within other React Elements as long as the whole thing is wrapped by in a single element.

For example

const paragraphs = (
<div id="i-am-the-outermost-element">
  <p>I am a paragraph.</p>
  <p>I, too, am a paragraph.</p>
</div>
);

VII. Render JSX

ReactDOM.render() is the most common way to render a JSX expression.

ReactDOM.render()‘s first argument should evaluate to a JSX expression, and it will be rendered to the screen.

Example 1:

ReactDOM.render(
<h1>Hello world</h1>
, document.getElementById('app'));

Example 2: JSX expression is a variable named myList

const myList = (
<ul>
  <li>Learn React</li>
  <li>Become a Developer</li>
</ul>
); ReactDOM.render( myList, document.getElementById('app') );