React JSX

 

As we have already seen that, all of the React components have a render function. The render function specifies the HTML output of a React component. JSX(JavaScript Extension), is a React extension which allows writing JavaScript code that looks like HTML. In other words, JSX is an HTML-like syntax used by React that extends ECMAScript so that HTML-like syntax can co-exist with JavaScript/React code. The syntax is used by preprocessors (i.e., transpilers like babel) to transform HTML-like syntax into standard JavaScript objects that a JavaScript engine will parse.

JSX provides you to write HTML/XML-like structures (e.g., DOM-like tree structures) in the same file where you write JavaScript code, then preprocessor will transform these expressions into actual JavaScript code. Just like XML/HTML, JSX tags have a tag name, attributes, and children.

Example

Here, we will write JSX syntax in JSX file and see the corresponding JavaScript code which transforms by preprocessor(babel).

JSX File

  1. <div>Hello JavaTpoint</div>  

Corresponding Output

 
  1. React.createElement(“div”null“Hello JavaTpoint”);  

The above line creates a react element and passing three arguments inside where the first is the name of the element which is div, second is the attributes passed in the div tag, and last is the content you pass which is the “Hello JavaTpoint.”

Why use JSX?

  • It is faster than regular JavaScript because it performs optimization while translating the code to JavaScript.
  • Instead of separating technologies by putting markup and logic in separate files, React uses components that contain both. We will learn components in a further section.
  • It is type-safe, and most of the errors can be found at compilation time.
  • It makes easier to create templates.

 

Share: