React JSX Syntax

JSX Syntax

JSX

JSX is a syntax extension to JavaScript. Use JSX to describe what the UI should look like.

Babel compiles JSX down to React.createElement() calls. So the output of JSX is React Element.

JSX Example

1
let heading=<h1>Hello React</h1>

Multiline JSX Example

1
2
3
4
let heading=
<h1>
Hello React
</h1>

For multi-line JSX, you can wrap the elements in parentheses for readability. It is not required to do this.

1
2
3
4
5
let heading=(
<h1>
Hello React
</h1>
)

Embedding JS Expression

Valide Javascript expression can be inserted inside the curly braces.

By default, ReactDOM escapes any values embedded in JSX before rendering them.

Example of Javascript Expression in JSX

1
2
3
4
5
6
const person = {firstname: 'John', lastname: 'Smith'}
const heading=(
<h1>
Hello {person.firstname}
</h1>
)

Another Example

1
2
3
4
5
6
7
<ul id="book-list">
{
data.books.map( (book) => {
return <li key={book.id}>{book.name} - {book.genre}</li>
})
}
</ul>

In JSX, curly braces is used to evaluate JavaScript expression during compilation.

Attributes

You can set attributes of a element with JSX.

You can have String literals as attribute value just like regular HTML syntax

1
const element = <a href="https://google.com">Google</a>

Or you can use Javascript expression as attribute value. Here src attribute is using a Javascript expression

1
const element = <img src={food.imgurl}></img>;

You should either use quotes (for string values) or curly braces (for expressions), but not both in the same attribute.

Special Attributes

class and for are both javascript’s keyworlds, they need to be changed to className and htmlFor attribute

1
2
3
<h1 className="redheading">
Hello {name}
</h1>

Comment

HTML Comment is invalid in JSX Syntax. So you can’t use <!-- --> to add comment in JSX.

1
2
3
4
5
6
7
8
const sometext = (
<div>
<!-- This is incorrect JSX Syntax -->
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
</p>
</div>
);

The correct way to add comment is to use regular JS comment /* */ in a curly brace.

1
2
3
4
5
6
7
8
const sometext = (
<div>
{/* JSX Comment */}
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit
</p>
</div>
);

Fragment

JSX Expression must have a parent.

JSX Expression without a parent is invalid

1
2
3
4
5
// invalid
let post = (
<h1>{heading}</h1>
<p>{body}</p>
);

You need to add a fragment (<> and </>) around the elements

1
2
3
4
5
6
let post = (
<>
<h1>{heading}</h1>
<p>{body}</p>
</>
);

It is equivalent to add React.Fragment element around the elemnts to produce valid JSX

1
2
3
4
5
6
let post = (
<React.Fragment>
<h1>{heading}</h1>
<p>{body}</p>
</React.Fragment>
);