What Is JSX?
February 14, 2023
JSX looks similar to HTML in syntax, but it's actually a syntax extension of JavaScript. Its feature is the fusion of UI and JavaScript logic - creating components. Although JSX is not mandatory in React development, it's widely used by most developers because it improves the development experience and allows React to display error and warning messages.
What is JSX?
JSX essentially generates React elements, and it's a syntactic sugar of
React.createElement(component, props, ...children);
The following example:
<MyButton color="blue" shadowSize={2}>
Click Me
</MyButton>
is equivalent to:
React.createElement(MyButton, { color: "blue", shadowSize: 2 }, "Click Me");
Why use JSX?
As previously mentioned, JSX is JavaScript, and using it means combining markup and logic. This appears to violate the principle of separation of concerns, where content presentation and logic should be separated. However, many modern websites are highly dynamic, and logic can affect content presentation. Combining content and logic using JSX ensures that both stay in sync when changes are made, and makes it easier when reusing code. Additionally, content that's not related to a component can be placed in another component, which allows changes in one component to be independent of another.
JSX Rules
- Return a single root element: If a component returns multiple elements, the elements must be wrapped in a parent element (for example, using
<div>
or a Fragment (<> and </>
))。 - All tags must be closed: JSX requires that all tags have an end tag, even for self-closing tags like
<img>
which should be written as<img/>
. - Almost all attribute names are in camelCase: JSX is eventually converted to JavaScript, and JavaScript has restrictions on variable names such as not using reserved words or hyphens. Therefore, many attribute names in JSX are written in camelCase. For example, if you want to add a CSS class, use
className
,stroke-width
should be written asstrokeWidth
.However, there are exceptions foraria-*
anddata-*
attributes, which should be written the same way as in HTML.