A syntax extension to JS.
const element = (
<h1 className='greeting'>
Hello, world!
</h1>
)
Babel compiles JSX to React.createElement()
calls that evaluate to
React elements.
The last example compiles (and is identical) to:
const element = React.createElement(
'h1',
{ className: 'greeting' },
'Hello, world!'
)
React.createElement()
essentially creates an object as in the
React element example.
JSX... :
-
Helps separate concerns (rather than technologies) with React components that contain both markup and logic.
-
Allows React to show more useful error and warning messages.
-
Prevents injection attacks - It is safe to embed user input in JSX.
const title = response.potentiallyMaliciousInput // This is safe: const element = <h1>{title}</h1>
-
You can put any valid JS expression inside the
{}
in JSX. JSX is an expression too.const name = 'Josh Perez' const element = <p>Hello, {name}</p>
-
Wrapp multi-line JSX in
()
to avoid auto;
insertion.return ( <p> Hello, {formatName(user)}! </p> )
-
You may also use
{}
to embed a JS expression in an attribute.const element = <img src={user.avatarUrl}></img>
-
React DOM uses
camelCase
property naming convention. E.g.,->class
className
.->tabindex
tabIndex
. -
JSX allows self-closing for any tag (
<img />
,<MyComponent />
).