-
JSX stands for
JavaScript XML
-
JSX is used by React to write
HTML-like code
-
JSX is converted to JavaScript via tools like
Babel
. (Because Browser understand JavaScript not JSX)
-
Improve code readability and writability
-
Error checking in advance (Type safety)
-
Support JavaScript expressions
-
Improved performance
-
Code reuseability
Babel
in React is used to transpile JSX syntax into reglar JavaScript which browser can understand.
-
In React, a fragment is a way to
group multiple children's
elements. -
Using a Fragment prevents the addition of unnecessary nodes to the DOM.
return(
<>
<div>This is a div</div>
<p>This is a paragraph</p>
<button>This is a button</button>
</>
)
The spread operator (...)
is used to expand or spread an array or object.
const props = {name: 'Hello', noun: 'World'};
return(
<>
<ChildComponent {...props}>
{/*<ChildComponent {props}> ❌*/}
</>
)
function ChildComponent(props){
return(
<div>
{props.name}, {props.noun}
</div>
)
}
- If / else statements
- Ternary operator
- && operator
- Switch statement
// If/else statements
function MyComponent() {
if (2 > 1) {
return "abc";
} else {
return "xyz";
}
}
// Ternary operator
function MyComponent() {
return 2 > 1 ? "abc" : "xyz";
}
// && operator
function MyComponent() {
return 2 > 1 && "abc";
}
// Switch statement
function MyComponent() {
const value = 2;
switch (value) {
case 2:
return "abc";
case 1:
return "xyz";
default:
return null;
}
}
map() method allows you to iterate over an array and modify its elements using a callback function.
function App() {
const numbers = [1, 2, 3, 4, 5];
return (
<>
{
numbers.map((number) => (
<div key={number}>{number * 2}</div>
))
// 2 4 6 8 10
}
</>
);
}
A callback function is a function passed as an argument to another function, which is then invoked within the outer function to complete a specific task.
-
No, browsers cannot directly interpret or understand JSX files.
-
Babel takes JSX and converts it into equivalent JavaScript code that browsers can understand.
Transpiler
- A Transpiler is a tool that converts source code from one high-level programming language(JSX) to another high-level programming language(JavaScript).
Example: Babel
Compiler
- A compiler is a tool that converts high-level programming language(Java) into a lower-level language(machine code or bytecode).
-
Yes, it's possible to use JSX without React by creating your own transpiler like Babel.
-
However, this is not recommended since JSX is tightly integrated with React and relies on many React-specific features.
Previous: File and Folder
Next: Components (Function & Class)