- 4 years ago
- Zaid Bin Khalid
- 6,582 Views
-
3
In this session, we will learn about JSX and why we use JSX in react JS with the help of code and examples.
What is JSX
JSX full form is JavaScript XML, which allows us to write HTML in React. JSX makes it easier for us to write and add HTML to React.
Coding JSX
Without any createElement and/or appendchild( ) methods, JSX allows us to write HTML elements in JavaScript and place it in the DOM. JSX makes it easier to write React applications and converts HTML tags into react elements.
Let’s demonstrate with two examples, with uses of JSX and the second without JSX:
//Example # 1
//With JSX
const myelement = <h1>I Love JSX!</h1>;
ReactDOM.render(myelement, document.getElementById('root'));
RUN EXAMPLE
//Example # 2
//Without JSX
const myelement = React.createElement('h1', {}, 'I do not use JSX!');
ReactDOM.render(myelement, document.getElementById('root'));
//RUN EXAMPLE
Expressions in JSX
With the help of JSX, you can easily write expression inside the { } brackets. JSX will help you to execute the expression and return the result, expression can be a React variable, or property, or any other valid JavaScript’s expression.
//EXAMPLE
Execute the expression 5 + 5:
const myelement = <h1>React is {5 + 5} times better with JSX</h1>;
//RUN EXAMPLE
Inserting a Large Block of HTML
You can easily write the HTML multiple lines inside:
//EXAMPLE
Create a list with three list items:
const myelement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>
);
//RUN EXAMPLE
One Top-Level Element
ONE top level element must be wrapped in the HTML code.
So if you like to write two headers, you must put them inside a parent element, like a div element
//EXAMPLE
Wrap two headers inside one DIV element:
const myelement = (
<div>
<h1>I am a Header.</h1>
<h1>I am a Header too.</h1>
</div>
);
//RUN EXAMPLE
An error occurred in JSX if the HTML is not correct, or if the HTML miss a parent element
Elements must be closed
HTML elements must be properly closed because the JSX only follows XML rules
//EXAMPLE
Close empty elements with />
const myelement = <input type="text" />;
//RUN EXAMPLE
Use of JSX in React:
Instead of regular JavaScript, the React uses JSX for templating. However, some points come with it which are mention below:
- It performs optimization while compiling code to JavaScript because it is faster.
- Most of the errors can be caught during compilation and it is also type-safe.
- If you are familiar with HTML, It makes it easier and faster to write templates.
- 4 years ago
- Zaid Bin Khalid
- 6,582 Views
-
3