JSX

    What is JSX?

    JSX is an extension to the JavaScript language that adds a new kind of expression, the JSX expression, used to create React elements (which we'll cover soon).

    JSX expressions are a concise syntax for calling the API, React.createElement(type, props, ...children).

    We can use JSX expressions anywhere we could use any other expression, e.g. in a return statement or variable assignment.

    Type

    Like XML, each JSX expression has a tag, e.g. <View />, which is then transformed into a call to React.createElement(View). In this case, View is the type of the element.

    On the right in the example above, we can see how our JSX expressions are compiled by babel.

    Props

    Any JSX attributes become props (parameters) of the React element. The value of an attribute can be a string, like foo="hello", or it can be any JavaScript expression when wrapped in curly braces, as in bar={baz} (which would set the value of the bar prop to baz).

    Children

    Any children elements should go between the opening tag, <View>, and closing tag </View>. Elements without children can use a self-closing tag, like <View />, as a shorthand.

    When a JSX element wraps to multiple lines, we often write it with parentheses around it, since it looks nicer.

    Interpolation

    Children are generally other elements, but can also be any other kind of expression if wrapped in curly braces, { ... }.

    Why JSX?

    The XML-like syntax is typically more concise, easier to read, and visually looks a little like the generated UI (both are tree-like).

    We don't have to use JSX, but there are few disadvantages, so we almost always use it.

    Want to learn React Native in-depth?

    If you like React Native Express, you'll love my new book, Fullstack React Native: The complete guide to React Native! Throughout the book, we'll build 7 full apps, covering complex topics like navigation, gestures, and native modules. We don't assume any knowledge of React or newer JavaScript language features, so you can dive right in regardless of your experience level. The book comes in PDF, EPUB and MOBI formats.