What is JSX in React | How JSX Works Internally in React | JSX Interview Questions
What is JSX
React JS – introduction to JSX and Internal Working, We will learn about JSX.JSX is One of basic aspect in react.It acts a kind of templating in react, but it is more than that. JSX is a syntactical extension to javascript, it helps to build your UI components. JSX is a preprocessor step that adds XML syntax to JavaScript. You can definitely use React without JSX but JSX makes React a lot more elegant.We must remember always React is a Library not a framework.
const element = <div class="wrapper">
<h1 color="blue" className="sidebar" >Hello, world! </h1>
<h2 color="blue" className="sidebar" >Hey Guys</h2>
</div>;
This code above is a combination of javascript and HTML. In case of normal coding perspective, it’s unusual. You can’t have javascript and Html together in a single place, but react doesn’t separate the technologies by putting markup and logic in two different places. Instead of that, it separates the concerns, and the concern here is How easy and How good is our UI?
How JSX Works Internally
Fundamentally the above JSX code gets compiled as:-
"use strict";
var element = React.createElement(
"div",
{ "class": "wrapper" },
" ",
React.createElement(
"h1",
{ color: "blue", className: "sidebar" },
"Hello, world!"
),
React.createElement(
"h2",
{ color: "blue", className: "sidebar" },
"Hey Guys"
)
);
Please Visit this link here to try and convert JSX to Browser compatible javascript.Babel converts the JSX to React.CreateElement code .Babel Converts Jsx Code in to a Javascript code that the browser understands.Look at the example below.
Some Must Read Posts
Few Points about JSX for Interview
- JSX is different from react, its an EmacScript feature provided to you to write your view.
- There can be only one parent and multiple child elements/components inside JSX.
- You must have an opening and closing elements in the parent component/element of JSX.
- We Can embed any javascript expression in JSX Any javascript expression and operator operations are valid in JSX.
Inline Styles in JSX:- With inline styles, you have to option to combine CSS syntax with JSX code.
var myStyle= {
color:'red',
backgroundColor:'black',
fontWeight:'bold'
};
var element= <div style={myStyle}>Hello World</div>;
Conclusion
We must always keep in mind “JSX doesn’t Separates Technologies it separates Concerns” .It helps us to write reusable code . Look at next Article on How to Setup React JS using JSX and Babel.
“Its Always Better To Learn and Share Instead Learn and Forget”