
Introduction to JSX
JSX (JavaScript XML) is an extension to JavaScript syntax that looks similar to HTML or XML. It’s a fundamental building block of React Native applications, allowing developers to write UI components in a familiar, HTML-like structure while leveraging the full power of JavaScript.
const element = <Text>Hello, React Native!</Text>;
This simple line of code demonstrates JSX – it looks like HTML/XML but is actually JavaScript under the hood. This chapter will help you understand how JSX in React Native works and how to use it effectively.
Why JSX?
Before diving deeper into JSX syntax, let’s understand why React uses JSX:
- Familiarity: If you’ve worked with HTML, JSX feels intuitive
- Visual clarity: UI structure is more visible compared to pure JavaScript
- Co-location: Keep rendering logic and UI together in the same component
- Type safety: JSX can catch many errors during compilation
Facebook (now Meta) created React with JSX to solve a fundamental problem: building large applications with data that changes over time. JSX allows developers to think about UI in terms of components rather than string templates or DOM manipulation.
JSX vs HTML: Key Differences
While JSX looks similar to HTML, there are several important differences:
- Self-closing tags: All tags can be self-closing in JSX
// Valid JSX
<View />
// Also valid JSX
<View></View>
- camelCase property naming: HTML attributes become camelCase props
// HTML: <div class="container" onclick="handleClick()">
// JSX:
<View className="container" onClick={handleClick} />
<Text>Count: {count + 1}</Text>
- JavaScript expressions: Use curly braces {} to embed JavaScript
<Text>Count: {count + 1}</Text>
- Components must return a single root element: All JSX must be wrapped in a parent element
/ Valid JSX
return (
<View>
<Text>Line 1</Text>
<Text>Line 2</Text>
</View>
);
// Invalid JSX - multiple root elements
return (
<Text>Line 1</Text>
<Text>Line 2</Text>
);
- React Native specific elements: Instead of HTML elements like <div> and <span>, React Native uses platform-agnostic components like <View> and <Text>
JSX Under the Hood
When you write JSX, it gets transformed into regular JavaScript through a process called transpilation. Let’s see what happens behind the scenes:
JSX code:
const element = <Text>Hello, world!</Text>;
Transpiled JavaScript:
const element = React.createElement(
 Text,
 null,
 "Hello, world!"
);
The transformation is handled by tools like Babel during the build process. Understanding this transformation helps explain why certain JSX rules exist and how JSX differs from templates in other frameworks.
React Native Component Types in JSX
In React Native applications, there are two main types of components you’ll use with JSX:
1. Core Components
These are the built-in components provided by React Native:
import { View, Text, Image, ScrollView, TextInput } from 'react-native';
function CoreComponentsExample() {
 return (
  <View>
   <Text>Hello!</Text>
   <Image source={require('./logo.png')} />
   <TextInput placeholder="Enter text" />
  </View>
 );
}
2. Custom Components
These are components you create yourself:
function Greeting(props) {
 return <Text>Hello, {props.name}!</Text>;
}
function App() {
 return (
  <View>
   <Greeting name="Alice" />
   <Greeting name="Bob" />
  </View>
 );
}
All React Native component names must start with a capital letter to distinguish them from built-in components.
JSX Expressions
JSX allows you to embed any JavaScript expression within curly braces {}. This is one of JSX’s most powerful features.
const name = 'John Doe';
const element = <Text>Hello, {name}!</Text>;
You can use more complex expressions too:
function getGreeting(user) {
 if (user) {
  return <Text>Hello, {user.name}!</Text>;
 }
 return <Text>Hello, Stranger!</Text>;
}
const element = getGreeting({ name: 'John Doe' });
Here are some examples of what you can put inside curly braces:
- Variables: {name}
- Arithmetic: {2 + 2}
- Function calls: {formatName(user)}
- Ternary expressions: {isLoggedIn ? ‘Profile’ : ‘Login’}
- Object properties: {user.firstName}
JSX Attributes
You can specify attributes in JSX similar to HTML:
// String literal
const element = <TextInput placeholder="Enter your name" />;
// JavaScript expression
const element = <Image source={require('./image.jpg')} />;
React Native uses a special attribute called style for styling components:
const element = (
 <Text style={{ color: 'blue', fontSize: 16 }}>
  Styled text
 </Text>
);
Notice that style takes a JavaScript object, which is why there are double curly braces: the outer pair for the JSX expression and the inner pair for the object literal.
Conditional Rendering in JSX
Since JSX is just JavaScript, you can use standard JavaScript techniques for conditional rendering:
If-Else with Variables
function Greeting(props) {
 const isLoggedIn = props.isLoggedIn;
 let greeting;
Â
 if (isLoggedIn) {
  greeting = <Text>Welcome back!</Text>;
 } else {
  greeting = <Text>Please sign in.</Text>;
 }
Â
 return <View>{greeting}</View>;
}
Inline Ternary Operator
function Greeting(props) {
 const isLoggedIn = props.isLoggedIn;
Â
 return (
  <View>
   {isLoggedIn
    ? <Text>Welcome back!</Text>
    : <Text>Please sign in.</Text>}
  </View>
 );
}
Logical && Operator
This technique works well when you want to render something or nothing:
function Notifications(props) {
 const unreadMessages = props.unreadMessages;
Â
 return (
  <View>
   <Text>Home</Text>
   {unreadMessages.length > 0 &&
    <Text>You have {unreadMessages.length} unread messages.</Text>
   }
  </View>
 );
}
Rendering Lists in JSX
You’ll often need to render lists of data in React Native. You can use JavaScript’s map() method to transform arrays into JSX elements:
function NumberList(props) {
 const numbers = props.numbers;
 const listItems = numbers.map((number) =>
  <Text key={number.toString()}>
   {number}
  </Text>
 );
Â
 return <View>{listItems}</View>;
}
Notice the key attribute above. This special prop helps React identify which items have changed, been added, or removed. Keys should be unique among siblings in a list.
JSX Fragments
Sometimes you don’t want to add an extra View container, but need to return multiple elements. React provides Fragments for this purpose:
import React, { Fragment } from 'react';
import { Text } from 'react-native';
function Example() {
 return (
  <Fragment>
   <Text>Line 1</Text>
   <Text>Line 2</Text>
  </Fragment>
 );
}
There’s also a shorthand syntax:
function Example() {
 return (
  <>
   <Text>Line 1</Text>
   <Text>Line 2</Text>
  </>
 );
}
This helps avoid unnecessary nesting in your component tree.
JSX Comments
Adding comments within JSX requires a specific syntax:
const element = (
 <View>
  {/* This is a JSX comment */}
  <Text>
   {/* Comments can go inside elements too */}
   Hello, world!
  </Text>
  {/*
   Multi-line
   comments
   work too
  */}
 </View>
);
Note that comments must be wrapped in curly braces because they are JavaScript expressions.
JSX Gotchas and Best Practices
1. className vs style
React Native doesn’t use CSS classes like web React does. Instead of className, you use the style prop with JavaScript objects:
// Web React (incorrect for React Native)
<div className="container">...</div>
// React Native
<View style={styles.container}>...</View>
2. Event handling differences
React Native uses specific event handlers suited for mobile:
// Web React
<button onClick={handleClick}>Click me</button>
// React Native
<TouchableOpacity onPress={handlePress}>
 <Text>Press me</Text>
</TouchableOpacity>
3. Inline styles are objects, not strings
// Incorrect
<Text style="color: red; font-size: 16px;">Text</Text>
// Correct
<Text style={{ color: 'red', fontSize: 16 }}>Text</Text>
4. No direct HTML elements
// Incorrect - these are web elements
<div>
 <span>Text</span>
</div>
// Correct - using React Native components
<View>
 <Text>Text</Text>
</View>
Practical Example: Building a Profile Card
Let’s bring everything together with a practical example:
import React from 'react';
import { View, Text, Image, StyleSheet, TouchableOpacity } from 'react-native';
function ProfileCard() {
 const user = {
  name: 'Jane Doe',
  role: 'Software Developer',
  avatar: require('./jane.jpg'),
  followers: 1250,
  following: 340
 };
Â
 const handlePress = () => {
  alert(`Following ${user.name}`);
 };
 return (
  <View style={styles.card}>
   <Image
    source={user.avatar}
    style={styles.avatar}
   />
   <View style={styles.textContainer}>
    <Text style={styles.name}>{user.name}</Text>
    <Text style={styles.role}>{user.role}</Text>
    <View style={styles.statsContainer}>
     <Text style={styles.statsText}>
      {user.followers} Followers • {user.following} Following
     </Text>
    </View>
   </View>
   <TouchableOpacity
    style={styles.button}
    onPress={handlePress}
   >
    <Text style={styles.buttonText}>Follow</Text>
   </TouchableOpacity>
  </View>
 );
}
const styles = StyleSheet.create({
 card: {
  backgroundColor: 'white',
  borderRadius: 12,
  padding: 16,
  flexDirection: 'row',
  alignItems: 'center',
  shadowColor: '#000',
  shadowOffset: { width: 0, height: 2 },
  shadowOpacity: 0.1,
  shadowRadius: 4,
  elevation: 2,
 },
 avatar: {
  width: 60,
  height: 60,
  borderRadius: 30,
 },
 textContainer: {
  marginLeft: 12,
  flex: 1,
 },
 name: {
  fontSize: 18,
  fontWeight: 'bold',
 },
 role: {
  fontSize: 14,
  color: '#666',
  marginBottom: 4,
 },
 statsContainer: {
  flexDirection: 'row',
 },
 statsText: {
  fontSize: 12,
  color: '#888',
 },
 button: {
  backgroundColor: '#1e90ff',
  paddingHorizontal: 16,
  paddingVertical: 8,
  borderRadius: 20,
 },
 buttonText: {
  color: 'white',
  fontWeight: 'bold',
 },
});
export default ProfileCard;
This example demonstrates many JSX concepts:
- Using component imports
- Embedding JavaScript expressions
- Working with props and state
- Event handling
- Conditional rendering
- Styling with StyleSheet
- Component composition
Summary
In this chapter, we’ve covered JSX fundamentals in React Native:
- JSX is a syntax extension for JavaScript that resembles HTML
- JSX gets transpiled to React.createElement() calls
- JSX allows embedding JavaScript expressions within curly braces
- React Native uses platform-specific components instead of HTML elements
- JSX requires proper nesting and single root elements
- Lists in JSX need unique key props
- JSX supports conditional rendering through JavaScript expressions
- Fragments allow returning multiple elements without extra containers
- Styling in React Native JSX differs from web React
Understanding JSX is crucial for React Native development because it’s the primary way you’ll describe your UI. As you continue through this book, you’ll build on these JSX foundations to create increasingly complex and interactive mobile applications.
Exercises
- Create a simple weather card component that displays the current temperature, condition, and an appropriate icon using JSX.
- Refactor this code to use conditional rendering for displaying different user statuses:
function UserStatus(props) {
 // Refactor this to conditionally show "Online", "Away", or "Offline"
 // based on a status prop
 return (
  <View>
   <Text>Status: Online</Text>
  </View>
 );
}
- Create a component that renders a list of todo items from an array, and applies different styles to completed versus incomplete items.
- Practice converting between HTML and React Native JSX by transforming this HTML snippet:
<div class="container">
 <h1 class="title">Hello World</h1>
 <p>This is a paragraph with <span class="highlight">highlighted</span> text.</p>
 <button onclick="handleClick()">Click Me</button>
</div>
Next Steps
In the next chapter, we’ll explore React Native’s core components in more detail, learning how to combine them to build more complex user interfaces for your mobile applications.
Related Articles:
- React Native vs Flutter in 2024: A Detailed Comparison
- Top 10 React Native Libraries You Must Know in 2024
- React vs React Native: A Deep Dive into Key Differences
- How to Set Up Navigation in React Native : Step-by-Step Guide
- What is Axios? Fetch vs Axios: What’s the Difference?
- React Native Environment Setup: A Beginner’s Step-by-Step Guide
- React Native Web: A Step-by-Step Guide to Cross-Platform Development