JSX - Javascript XML in React

react

React is developed on the fact that rendering logic should be coupled with other UI logic(events, state management) and should be managed together.

For this reason, instead of separating technologies(separate files for HTML and javascript), react uses a syntax extension of javascript, JSX - Javascript XML. Using JSX, you can write markup inside Javascript, providing you with a superpower to write logic and markup of a component inside a single .jsx file.

1
2
3
4
function greeting(user) {
  //warning: JSX in next line...
  return <h1>{user}, How are you!!!</h1>;
}

In the above example,

1
    return <h1>{user}, How are you!!!</h1>;

"<h1>{user}, How are you!!!</h1>" looks like HTML but is actually JSX.

All JSX returns a react element which will be rendered as a DOM node by virtual DOM.

You can write/embed a javascript expression inside JSX using "{}" curly brackets. In the above example, {user} will be evaluated before returning the react element.

JSX are also javascript expressions, which compiles to React.createElement() function calls. And these functions(React.createElement()) return javascript objects. The returned objects describe what will be rendered on the screen and are called react elements.

Here is the three-step process from JSX to react element.

  1. Let's consider the following code written in JSX:
1
<div className="greeting">Hello, how are you?</div>
  1. JSX compiles to React.createElement() function calls:
1
2
3
4
5
6
7
React.createElement(
  "div", 
    {
      className: "greeting"
    }, 
    "Hello, how are you?"
);

We will get into the details of the React.createElement() in another article.

  1. React.createElement function calls returns react element:
1
2
3
4
5
6
7
{ 
  type: 'div',
  props: {
    children: 'Hello, how are you?', 
    id: 'greeting' 
  }
}

A react element is a javascript object representing a piece of UI on the screen.

When the above react element is rendered by the virtual DOM to the DOM, the following node will be created and attached to the DOM:

1
<div class="greeting">Hello, how are you?</div>

React virtual dom uses react elements to decide what will be rendered on the screen and thus manipulate the real dom.

Remember, JSX is not required for writing a react application but is recommended by the official documentation.

Summary

In this article we learned:

  • What is JSX?
  • Why React use JSX?
  • What is React Element?
  • What are the steps involved from writing JSX to creating a node on the DOM?

If you liked this article, please upvote and recommend it to show your support. Feel free to ask any questions in the comments below.


We publish articles on web development and technology frequently. Consider subscribing to our newsletter or follow us on our social channels (twitter, Facebook, LinkedIn).

Share and support us

Share on social media and help us reach more people