JSX looks similar to HTML, but it's not. It's a syntex extension to JavaScript.
JSX produces React "elements".
React JSX doesn't put markup and logic in seperate files. It combines them to one unit called "component".
Component contains both markup and logic.
Using JSX is not essential, but helpful when working with UI inside the JavaScript code.
It's available to write JavaScript code in curly braces
React show many useful errors and warning messages.
Because JSX is one of JavaScript expressions, if statements and for loop can be written in JSX.
function personName(person) {
return user.firstName + ' ' + user.lastName;
}
const person = {
firstName: 'Harper',
lastName: 'Perez'
};
function sayHello(person){
if(person){
return <h1>Hello, {personName(person)}!<h1>
}
return <h1>Hello, Stranger.</h1>;
}
const element = <div tabIndex="0"></div>;
const element = <img src={user.avatarUrl}></img>;
JSX is closer to JavaScript than to HTML. So React DOM uses camelCase to name the variable.
Even thoguh it looks similar to JavaScript, but it's different with JavaScript. So it's not allowed to use same keyword with JavaScript.
JSX can express Object. Babel compiles JSX down to React.createElement() calls.
These two examples are same.
const element = (
<h1 className="greeting">
Hello, world!
</h1>
);
const element = React.createElement(
'h1',
{className : 'greeting'},
'Hello, world!'
);
const element = {
type: 'h1',
props: {
className: 'greeting',
children: 'Hello, world!'
}
};
JSX prevents injection attacks like XSS(cross-site-scripting) attacks.
React DOM escapes any values in JSX before rendering them. Escape means change the characters to the new strings. Because it change the characters to the new strings, the injection attack code may be written down in program but it can't be worked properly cause it's written down with the new strings.
It is safe to embed user input in JSX.