JSX is a syntax extension for JavaScript. It was written to be used with React. JSX code looks a lot like HTML.
What does “syntax extension” mean?
In this case, it means that JSX is not valid JavaScript. Web browsers can’t read it!
If a JavaScript file contains JSX code, then that file will have to be compiled. That means that before the file reaches a web browser, a JSX compiler will translate any JSX into regular JavaScript.
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, 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.
JSX Elements And Their Surroundings
JSX elements are treated as JavaScript expressions. They can go anywhere that JavaScript expressions can go.
That means that a JSX element can be saved in a variable, passed to a function, stored in an object or array…you name it.
Here’s an example of a JSX element being saved in a variable:
const navBar = <nav>I am a nav bar</nav>;
Here’s an example of several JSX elements being stored in an object:
const myTeam = {
center: <li>Benzo Walli</li>,
powerForward: <li>Rasha Loa</li>,
smallForward: <li>Tayshaun Dasmoto</li>,
shootingGuard: <li>Colmar Cumberbatch</li>,
pointGuard: <li>Femi Billon</li>
};
Attributes In JSX
JSX elements can have attributes, just like HTML elements can.
A JSX attribute is written using HTML-like syntax: a name, followed by an equals sign, followed by a value. The value should be wrapped in quotes, like this:
my-attribute-name="my-attribute-value"
Here are some JSX elements with attributes
<a href="http://www.example.com">Welcome to the Web</a>;
const title = <h1 id="title">Introduction to React.js: Part I</h1>;
A single JSX element can have many attributes, just like in HTML:
const panda = <img src="images/panda.jpg"
alt="panda" width="500px" height="500px" />;
Top comments (0)