JSX (JavaScript) explained

JSX (JavaScript XML, formally JavaScript Syntax eXtension) is an XML-like extension to the JavaScript language syntax.[1] Initially created by Facebook for use with React, JSX has been adopted by multiple web frameworks.[2] [3] Being a syntactic sugar, JSX is generally transpiled into nested JavaScript function calls structurally similar to the original JSX.

Markup

An example of JSX code:const App = =>

Nested elements

Multiple elements on the same level need to be wrapped in a single React element such as the <nowiki><div></nowiki> element shown above, a fragment delineated by <nowiki><Fragment></nowiki> or in its shorthand form <nowiki><></nowiki>, or returned as an array.[4] [5] [6]

Attributes

JSX provides a range of element attributes designed to mirror those provided by HTML. Custom attributes can also be passed to the component.[7] All attributes will be received by the component as props.

JavaScript expressions

JavaScript expressions (but not statements) can be used inside JSX with curly brackets {}:[8]

The example above will render:

11

Conditional expressions

If–else statements cannot be used inside JSX but conditional expressions can be used instead.The example below will render as the string 'true' because i is equal to 1.const App = => The above will render:

true

Functions and JSX can be used in conditionals:[9] const App = =>

The above will render:

Section 1

(first)

Section 2

Section 3

Code written in JSX requires conversion with a tool such as Babel before it can be understood by web browsers.[10] [11] This processing is generally performed during a software build process before the application is deployed.

See also

Notes and References

  1. Web site: Draft: JSX Specification. JSX. Facebook. 7 April 2018.
  2. Book: Larsen, John. React Hooks in Action With Suspense and Concurrent Mode. 2021. Manning . 978-1720043997.
  3. Book: Wieruch, Robin. The Road to React . Leanpub. 978-1720043997.
  4. Web site: React v16.0§New render return types: fragments and strings . Clark . Andrew . September 26, 2017 . React Blog.
  5. Web site: React.Component: render . React.
  6. Book: Wieruch, Robin. The Road to React . Leanpub. 978-1720043997.
  7. Web site: React v16.0§Support for custom DOM attributes . Clark . Andrew . September 26, 2017 . React Blog.
  8. Book: Wieruch, Robin. The Road to React . Leanpub. 978-1720043997.
  9. Book: Wieruch, Robin. The Road to React . Leanpub. 978-1720043997.
  10. Book: Fischer, Ludovico. React for Real: Front-End Code, Untangled. 2017-09-06. Pragmatic Bookshelf. 9781680504484. en.
  11. Book: Larsen, John. React Hooks in Action With Suspense and Concurrent Mode. 2021. Manning . 978-1720043997.