Before you go, check out these stories!

0
Hackernoon logoWhat’s the Deal with JSX by@tayomadein

What’s the Deal with JSX

Author profile picture

@tayomadeinTayo Madein

Photo by Émile Perron on Unsplash

Since I began learning/using React, I have come across some new terms like JSX. JSX (aka JavaScript eXtension), is a JavaScript syntax extension that allows us to write JavaScript that looks like XML. It is well recommended and popularly used with React. Similar to XML, JSX has tag name, attributes and children. JSX is converted into browser-compatible JavaScript using transpilers (like React JSX, jsx-transform, Babel).

Let’s take a look at an example of JSX:

<MyExample className=”example”>
<p>Hello World! {2+2}</p>
</MyExample>

Breaking it Down

  • It has a tag name MyExample — Can be a user-defined component or a built-in component eg <div>, <p>. User-defined component should be capitalized because JSX considers lower-case tag names as HTML tags.
  • It has an attribute className — className is used instead of the traditional DOM class because class, like for, is reserved in Javascript and JSX is an extension of Javascript. A tag can have 0…many attributes and they follow camelCase property naming convention.
  • It has one child <p> — a tag can have multiple children including other JSX tags.
  • It contains a JavaScript expression {2+2} — You can embed any JavaScript expression in JSX by wrapping it in curly braces {}.

[PS: You can have a self-enclosing tag if it has no children ie <MyExample /> ]

Consider JSX as shorter and more natural way to write a React.createElement() declaration because at runtime, the example above is converted to:

React.createElement(
MyExample,
{ className: "example" },
React.createElement(
"p",
null,
"Hello World!",
2+2
);
);

While you can still create React elements using React.createElement, I find JSX to be easier to pick up especially if you’re coming from a HTML + CSS background.

In the past, experts frowned at combining JavaScript and markup in the same place, I personally found it unsettling at first. However, since I started using react, I have realized that JSX helps me to easily translate my UI designs into code and have a better understanding of the UI’s logic (one of the benefits of JSX).

If you want some in-depth material on JSX’s usage in React, check this out.

Please leave a comment below if you have any questions or contributions.

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.