Table of contents
Why JSX in ReactJS?
JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React. It is a syntax extension to JavaScript. JSX may remind you of a template language, but it comes with the full power of JavaScript.
React embraces the fact that rendering logic is inherently coupled with other UI logic: how events are handled, how the state changes over time, and how the data is prepared for display. Instead of artificially separating technologies by putting markup and logic in separate files, React separates concerns with loosely coupled units called “components” that contain both.
React doesn’t require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code. It also allows React to show more useful error and warning messages.
Here is a Minimal Example of JSX Code
const myelement = <h1>I Love JSX!</h1>;
ReactDOM.render(myelement, document.getElementById('root'));
Here is an Example of Some Codes Without JSX
const myelement = React.createElement('h1', {}, 'I do not use JSX!');
ReactDOM.render(myelement, document.getElementById('root'));
You can put any valid JavaScript expression inside the curly braces in JSX. For example, 2 + 2, user.firstName
, or formatName(user)
are all valid JavaScript expressions.
In the example below, we embed the result of calling a JavaScript function, formatName(user)
, into an <h1>
element.
function formatName(user) {
return user.firstName + ' ' + user.lastName;
}
const user = {
firstName: 'Harper',
lastName: 'Perez'
};
const element = (
<h1>
Hello, {formatName(user)}!
</h1>
);
ReactDOM.render(
element,
document.getElementById('root')
);
Brief Explanations On How JSX Is Used In ReactJS:
- JSX allows us to write HTML elements in JavaScript and place them in the DOM without any
createElement()
and/orappendChild()
methods.
JSX converts HTML tags into react elements.
After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects.
This means that you can use JSX inside of if statements and for loops, assign it to variables, accept it as arguments, and return it from functions.
Example:
function getGreeting(user) {
if (user) {
return <h1>Hello, {formatName(user)}!</h1>;
}
return <h1>Hello, Stranger.</h1>;
}
- You may use quotes to specify string literals as attributes:
const element = <a href="https://www.reactjs.org"> link </a>;
- You may also use curly braces to embed a JavaScript expression in an attribute.
Example:
const element = <img src={user.avatarUrl}></img>;
Don’t put quotes around curly braces when embedding a JavaScript expression in an attribute. You should either use quotes (for string values) or curly braces (for expressions), but not both in the same attribute.
- Since JSX is closer to JavaScript than to HTML, React DOM uses camelCase property naming convention instead of HTML attribute names.
For example, class
becomes className
in JSX, and tabindex
becomes tabIndex
.
- Specifying Children with JSX
If a tag is empty, you may close it immediately with />
, like XML
Example:
const element = <img src={user.avatarUrl} />;
- JSX tags may contain children.
Example:
const element = (
<div>
<h1>Hello!</h1>
<h2>Good to see you here.</h2>
</div>
);
- JSX Prevents Injection Attacks.
It is safe to embed user input in JSX. Here is an example below:
const title = response.potentiallyMaliciousInput;
// This is safe:
const element = <h1>{title}</h1>;
By default, React DOM escapes any values embedded in JSX before rendering them. Thus, it ensures that you can never inject anything that’s not explicitly written in your application. Everything is converted to a string before being rendered. This helps prevent XSS (cross-site-scripting) attacks.
- JSX Represents Objects.
Babel compiles JSX down to React.createElement()
calls.
React.createElement()
performs a few checks to help you write bug-free code, but essentially it creates an object like this:
Note: this structure is simplified.
const element = {
type: 'h1',
props: {
className: 'greeting',
children: 'Hello, world!'
}
};
These objects are called “React elements”. You can think of them as descriptions of what you want to see on the screen. React reads these objects and uses them to construct the DOM and keep it up to date.
- React supports
if
statements, but not inside JSX.
To be able to use conditional statements in JSX, you should put the if
statements outside the JSX, or you could use a ternary expression instead.
Example using conditional statements:
const x = 5;
let text = "Goodbye";
if (x < 10) {
text = "Hello";
}
const myelement = <h1>{text}</h1>;
Example using ternary expression:
const x = 5;
const myelement = <h1>{(x) < 10 ? "Hello" : "Goodbye"}</h1>;