In this article, you will get answers to the following questions and learn more deeply about JSX.
- What is JSX?
- Why JSX?
- Can you use JSX without React?
- Is Babel needed for JSX?
- What is Babel?
- How to write JSX Comments?
- JSX Example
- How to pass variable value in JSX?
- How to Pass object value?
What is JSX?
JSX stands for "JavaScript XML". JSX allows you to write HTML and JavaScript objects, variables, and arrays together. The alternative definition of JSX is a syntax extension to JavaScript. It looks like template-based writing with the full force and power of JavaScript.
Why JSX?
JSX converts HTML tags into react elements. JSX finds it helpful as a visual aid when working with UI inside the JavaScript code.
JSX Advantages
- JSX performs optimization while compiling the source code to JavaScript.
- Compile time error view.
- Faster than normal JS.
Can you use ReactJS without JSX?
Yes, JSX is not mandatory for ReactJS, but JSX makes it easier to write ReactJS Applications. JSX helps you to write HTML and JavaScript together.
Is Babel needed for JSX?
Yes, Babel is required for compiling JSX into React.
What is Babel?
Babel is a free and open-source JavaScript transcompiler that is mainly used to convert ECMAScript 2015+ code into backward-compatible JavaScript code that can be run by older JavaScript engines.
How to write JSX Comments?
You cannot just use HTML comments inside of JSX because it read like real DOM nodes.
<!—This is HTML Comment ->
You can write single-line comment and multiline comment using JSX style. The comment starts with /* and ends with *\ it should be wrapped in curly braces.
Single Line comment example,
{/* A JSX single line comment */}
Multi-line comment example,
{/*
JSX
Multi-line
comments
*/}
JSX Example
How to pass variable value in JSX?
Example 1
const FriendName = ‘Ashish Kalla’;
const HelloFriend = <h2>Hello, {FriendName}</h2>;
Code Explanation
- Declared a variable called FriendName and assigned the value ‘Ashish Kalla’.
- Now using JSX we pass the variable value or embed the variable value into H2 Element using curly braces.
How to Pass object value?
Example 2
function Friend({data}) {
return (
<div>
<h2>{data.fullname}</h2>
<h2>{data.age}</h2>
<h2>{data.mobile}</h2>
</div>
);
}
export default function App() {
const obj = {fullname: 'Suhana Kalla', age: 12, mobile: '9869166077'};
return (
<div>
<Friend data={obj} />
</div>
);
}
Code Explanation
- In the APP component we created object with properties of FullName, Age, and Mobile.
- Pass the object to FRIEND component.
- You can see a component is a mixture of HTML and JavaScript that’s called JSX.