Basic JSX Syntax

The React library uses a JavaScript syntax extension called JSX. JSX syntax in React looks like a combination of JavaScript and HTML. Some examples of basic JSX syntax can be seen below.

JSX elements are treated as expressions, and therefore they can be stored in a variable, like the below example. Note the use of single quotes around the element value should now exist.

const element = <p>I am an element</p>;

Because JSX is not valid JavaScript, web browsers are not able to understand the syntax, and so a JSX compiler will translate any JSX into regular JavaScript.

JSX elements can be also contain children. If the expression take up more than one line, the expression must be wrapped within a pair of parentheses.

const element = ( 
    <div>
        <p>I am an element</p>
    </div>
);

It should also be noted that JSX expressions should only contain one outermost element. The above example is valid, as the <div> element is used as the outermost element. The outermost elements should also match.

A couple of example below show invalid JSX syntax.

const element = ( 
    <p>I am an element</p>
    <p>I am another element</p>
);

const secondElement = ( 
    <div>
         <p>I am an element</p>
         <p>I am another element</p>
    </span>
);

Similar to HTML, you can have JSX attributes attached to an element.

const element = <p id="element-foo">I am an element with an ID attribute</p>;

You may also use curly braces to embed a JavaScript expression in an attribute.

const element = <img src={user.profileImageUrl}></img>;

React uses the createElement function from the React global to compile JSX syntax to JavaScript so that it can be understood by web browsers.

This function is what is used to compile JSX to JavaScript.

Therefore defining an element like the below.

const element = ( 
     <p>I am an element</p>
);

Is the same as doing:

const element = React.createElement(
  'p',
  null,
  'I am an element'
);

What happens after we declare elements? They need to be rendered. React does this by using the render() function of the ReactDOM global.

const element = ( 
    <p>I am an element</p>
);

ReactDOM.render(
    element,
    document.getElementById('root')
);

The code above will render into a DOM element with the id of root, so you need a <div id="root"></div> somewhere in your HTML file.

As JSX syntax in React is compiled using the createElement function, technically JSX isn’t necessarily needed to be used in React. However it is popular amongst developers due to it being visually easier to debug potential errors and warnings, as well as improving readability. Learning Basic JSX Syntax will help you learn how React compiles the language into JavaScript.