JSX is short for Javascript XML. Basically, JSX allows us to write HTML in React.
Why JSX?
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 (creating separate .css, .html, .js files), React separates concerns with loosely coupled units called components that contain both.
To learn more about components, check out this article:
React doesnโt require using JSX, but most people think itโs pretty helpful to use JSX.
Embedding Expressions in JSX
In the example below, we declare a variable called name and then use it inside JSX by wrapping it in curly braces:
We can put any valid Javascript expression inside curly braces in JSX.
To learn more about expressions, check out this article: expressions.
JSX is an Expression Too
After compilation, JSX expressions become regular Javascript function calls and evaluate to Javascript objects.
Warning:
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, onclick becomes onClick.
Specifying Children with JSX:
If a tag is empty, we can close it immediately with />
like XML:
JSX represents objects:
Babel compiles JSX down to React.createElement()
calls.
These two examples are identical:
React.createElement()
performs a few checks to help us write bug-free code but essentially it creates an object like this:
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.
And thatโs it for this article, I hope you enjoyed and learned a lot.
๐ฌ Leave a comment