JSX Syntax

The JSX syntax was introduced by the same people who created React.
It is designed to simplify working with React components.
At first glance it looks like a mix of HTML and JavaScript
What looks like HTML is just a familiar XML syntax that is used to define a component and its position inside the markup.

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

Inside JSX expressions, attributes can be inserted very easily.

const myText = "Monday" 
const element = <h1 text={myText}>Hello World</h1>

Syntax Features

class becomes className
for becomes htmlFor
attributes that contain a dash
camelcase is the new standard
onchange becomes onChange
onclick becomes onClick

.JSX File Extension

Wrapping Components

This JSX snippet wraps two components inside a div tag.


Transpiling JSX

A browser cannot execute javascript files that contain JSX code
These JSX files must first be transpiled into regular JavaScript.
The most popular tool for transpiling is Babel.

JSX is Optional

Every line of JSX code can be written in plain JavaScript
This is JSX code

   <div id="test">
      <h1>My Heading</h1>
      <p>Some Text</p>

is equivalent to this javascript code

   React.createElement("div", { className: "test" },
      React.createElement("h1", null, "My Heading")
      React.createElement("p", null, "Some Text"}

JSX has inline styles

© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext