In this tutorial you will learn about the ReactJS JSX and its application with practical example.
ReactJS JSX
JSX is basically a syntax extension of JavaScript which looks very similar to XML. JSX code looks similar to HTML but it is a mix of standard JavaScript and HTML. JSX is not implemented by engines or browsers, instead it is used by various preprocessors (transpilers) to be transformed into standard JavaScript. JSX tags can also have a tag name, attributes, and children similar to XML and HTML. In JSX, attribute value can be passed as simple string enclosed in quotes otherwise we need to wrap the value in braces enclosed as JavaScript expression.
JSX is basically a syntactic sugar for the React.createElement function, where JSX code is finally transpiled into pure JavaScript function calls with React.createElement.
Example:-
Here is simple JSX code, which is finally compiled into React code as following –
JSX
1 2 3 |
<div> <p>Welcome to W3Adda!</p> </div> |
React Code
1 2 3 4 5 6 7 8 9 |
React.createElement( "div", null, React.createElement( "p", null, "Welcome to W3Adda!" ) ); |
Why JSX?
It is not mandatory to use JSX while working with React, we can definitely use the plain JavaScript code. But JSX makes React more elegant and JSX has its own advantages.
- JSX is faster than standard JavaScript, because it optimize the source code while compiling it.
- JSX code is much more readable than the plain Javascript.
- JSX is easy to learn and write in comparison to JavaScript.
and then you transpile the JSX into pure JavaScript function calls with React.createElement.