Skip to main content

Rendering Lists and Conditional UI in React Native

Your goal: Display a collection of books from data and show useful UI when that collection is empty.

Before you begin: Complete Styling and Flexbox. Open the same Expo project and run npx expo start. Keep the reusable BookCard and its local read/unread state.

By the end, you will be able to:

  • Describe a book with an object and a collection with an array.
  • Render repeated cards with map() and identify them with stable keys.
  • Use FlatList for a scrolling collection and handle empty data.
  • Choose between if, a ternary, and && for conditional UI.
  • Explain why a stable key does not save a card’s state indefinitely.

Move the books into data​

The previous screen repeated these three components inside a ScrollView:

The previous screen’s three cards
<BookCard title="The Hobbit" author="J. R. R. Tolkien" />
<BookCard title="A Wizard of Earthsea" author="Ursula K. Le Guin" />
<BookCard title="The Secret Garden" author="Frances Hodgson Burnett" />

An object groups named values for one thing: a book has a title, an author, and now an ID. An array holds an ordered collection of values, such as our three book objects.

Put the following data outside your screen component, after the imports. The complete example later includes it too.

Describe the books once
type Book = {
id: string;
title: string;
author: string;
};

const books: Book[] = [
{ id: 'hobbit', title: 'The Hobbit', author: 'J. R. R. Tolkien' },
{ id: 'earthsea', title: 'A Wizard of Earthsea', author: 'Ursula K. Le Guin' },
{ id: 'secret-garden', title: 'The Secret Garden', author: 'Frances Hodgson Burnett' },
];

Book describes the expected shape of each object. Book[] means an array of books. Square brackets enclose the collection; each pair of braces encloses one book. Reading book.title gets that object’s title.

The IDs are explicit strings assigned to these entries. Each book needs a unique ID within this collection, and that ID should stay the same when the book moves or its title changes. An ID identifies the entry; its array index only describes its current position.

Render a card for each book with map()​

Replace the three manual cards inside the previous lesson’s ScrollView with this expression:

Inside the existing ScrollView, after the heading
{books.map(book => (
<BookCard
key={book.id}
title={book.title}
author={book.author}
/>
))}

map() calls the function once for each array item, in order, and collects its returned values into a new array. Here each returned value is JSX for a BookCard. React renders that array of elements. Adding another book object now adds another card without copying the card markup. The parentheses after => return the JSX directly; a function body with braces would need an explicit return.

Give React a stable key​

key={book.id} lets React match sibling items across renders. Keys must be unique among siblings and stable for the same item. React uses key itself; it is not an ordinary prop passed to BookCard. If a component needs an ID for its own logic, pass a separate prop such as bookId and declare it in the props type.

Imagine removing The Hobbit from the beginning of the data:

Book IDIndex beforeIndex after
hobbit0Removed
earthsea10
secret-garden21

Earthsea is still the same book, even though its index changed. Using key={index} would identify positions instead of books, which can attach a mounted card’s state to the wrong book after insertion, removal, or reordering. Avoid key={Math.random()} too: a new key on every render makes React recreate the card and reset its state. Keep IDs in the data. See React’s rendering lists guide.

Choose map() or FlatList​

map() builds an array of JSX; it does not provide scrolling. In the previous screen, ScrollView supplies scrolling and mounts all its children. That is reasonable for a small, known set of cards.

For a collection that may become long, React Native’s FlatList manages scrolling and renders content incrementally. This approach is called virtualization: the list keeps a window of active items around the visible area instead of mounting every item in a large collection immediately. Mounting adds a component instance to the interface; unmounting removes it and discards its local state. It can remove offscreen items from that window. See VirtualizedList.

ApproachSuitable forWhat happens
map() inside ScrollViewA short collection in a small screenAll mapped children are mounted together.
FlatListA collection that may grow into a long scrolling listThe list manages incremental rendering and scrolling.

Three books do not require virtualization for speed. We are learning the collection API so the screen can grow.

Start with three FlatList props​

Import FlatList from react-native. This fragment replaces the old ScrollView inside your safe-area container; it assumes the books array and BookCard already exist:

A minimal list
<FlatList
data={books}
renderItem={({ item }) => (
<BookCard title={item.title} author={item.author} />
)}
keyExtractor={book => book.id}
/>
  • data supplies the array.
  • renderItem receives an object; { item } pulls out the current book and returns its card.
  • keyExtractor returns the stable string key for each item. Here it replaces the explicit key on the mapped cards.

Do not wrap this vertical FlatList in a vertical ScrollView. Let one list own scrolling. To keep the heading with the scrolling content, the full example uses ListHeaderComponent.

Two more useful props are ListEmptyComponent, which supplies UI for an empty array, and ItemSeparatorComponent, which renders a small gap or divider between items, but not before the first or after the last. Read the FlatList reference.

Choose what to render​

Conditional rendering means choosing UI based on a value. Our card already uses isRead to choose its status and button label. These are three ways to express that choice; the short examples are alternatives to study, not extra components required by the full screen.

1. Use if for separate return paths​

A small standalone status component
import { Text } from 'react-native';

function ReadStatus({ isRead }: { isRead: boolean }) {
if (isRead) {
return <Text>Read</Text>;
}

return <Text>Unread</Text>;
}

The if selects one return path. You could pass the card’s state as <ReadStatus isRead={isRead} />. An if is a statement, so place it before a return rather than directly inside JSX braces. Keep Hooks such as useState at the top level, before any conditional return.

2. Use a ternary to choose between two values​

Inside BookCard’s JSX
<Text>{isRead ? 'Read' : 'Unread'}</Text>

The expression chooses 'Read' when true and 'Unread' when false. Writing isRead ? 'Read' : 'Not read' would make the same choice with different wording; we keep Unread to match earlier lessons. A ternary is useful when both states should show a label.

3. Use logical AND to show something or nothing​

An optional line inside BookCard’s View
{isRead && <Text>You finished this book.</Text>}

When isRead is true, the line appears. When false, React renders nothing for that expression. Likewise, isRead && <Text>Read</Text> shows a label only for read books; unlike the ternary, it supplies no unread label.

Our conditional style array follows the same idea:

The existing status label
<Text style={[styles.status, isRead && styles.readStatus]}>
Status: {isRead ? 'Read' : 'Unread'}
</Text>

The base style always applies; readStatus adds the green colors only when true. This changes appearance without hiding the label.

Compare numbers explicitly

Avoid count && <Text>Books available</Text>. JavaScript returns 0 when count is zero, and React does not treat that number like false. It can render a stray zero; in a native View, a bare number can also cause a text-outside-Text error.

Use a boolean condition instead:

{count > 0 && <Text>Books available</Text>}

Here count could be books.length, the number of entries. A zero count now produces false, which React skips.

See React’s conditional rendering guide for these patterns.

Give an empty collection a useful message​

An empty array is valid data. Without an explanation, a blank screen can look broken. A friendly empty state tells the reader what happened and what they can do next.

Add this prop to FlatList
ListEmptyComponent={
<Text>Your reading list is empty. Add a book to get started.</Text>
}

FlatList selects this UI when data has no entries. It disappears when there are books. The complete example gives it the same card styling and explains that, for this learning app, books are added by editing the array.

Understand the lifetime of card state​

We keep useState(false) inside BookCard, so each mounted card has its own toggle. Stable keys help React associate that state with the correct book across updates while the component is retained in the tree. They do not store state outside the component’s lifetime. See React’s preserving and resetting state guide.

A virtualized list can unmount a card—remove its component from the rendered tree—when it leaves the render window. When mounted again, that card can start with false again. Not every offscreen card is immediately unmounted, and with only three books you may never see this happen. Removing a book from the data or fully reloading the app can also discard its local state. The FlatList documentation explicitly notes this limitation.

Looking Ahead

Later lessons can keep read/unread values in the parent’s book collection so they survive individual card unmounts. Saving progress across app restarts would require persistent storage too. A read/unread filter needs access to those values at the collection level, so we leave it for that later step. Local card state remains our only approach here.

Run the complete Reading List​

Replace src/app/index.tsx with the following code, or use the same screen file as the previous lesson if your template differs. Keep the existing Expo Router layout and safe-area setup. HomeScreen is the default export for this route; changing the function name does not change its URL.

The screen keeps the original books, flexible card layout, decorative emoji, and accessible button labels. It uses FlatList instead of ScrollView, and a subtitle that still makes sense when the collection is empty or grows.

src/app/index.tsx — complete example
import { useState } from 'react';
import { FlatList, Pressable, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';

type Book = {
id: string;
title: string;
author: string;
};

const books: Book[] = [
{ id: 'hobbit', title: 'The Hobbit', author: 'J. R. R. Tolkien' },
{ id: 'earthsea', title: 'A Wizard of Earthsea', author: 'Ursula K. Le Guin' },
{ id: 'secret-garden', title: 'The Secret Garden', author: 'Frances Hodgson Burnett' },
];

type BookCardProps = {
title: string;
author: string;
};

function BookCard({ title, author }: BookCardProps) {
const [isRead, setIsRead] = useState(false);
const buttonLabel = isRead ? 'Mark as unread' : 'Mark as read';

return (
<View style={styles.card}>
<View style={styles.bookRow}>
<Text
style={styles.bookIcon}
accessible={false}
accessibilityElementsHidden={true}
importantForAccessibility="no"
>
📖
</Text>
<View style={styles.details}>
<Text style={styles.bookTitle}>{title}</Text>
<Text style={styles.author}>{author}</Text>
</View>
</View>
<Text style={[styles.status, isRead && styles.readStatus]}>
Status: {isRead ? 'Read' : 'Unread'}
</Text>
<Pressable
style={({ pressed }) => [styles.button, pressed && styles.buttonPressed]}
onPress={() => setIsRead(previous => !previous)}
accessibilityRole="button"
accessibilityLabel={buttonLabel + ': ' + title}
>
<Text style={styles.buttonText}>{buttonLabel}</Text>
</Pressable>
</View>
);
}

export default function HomeScreen() {
return (
<SafeAreaView style={styles.screen}>
<FlatList
data={books}
keyExtractor={book => book.id}
renderItem={({ item }) => (
<BookCard title={item.title} author={item.author} />
)}
contentContainerStyle={styles.content}
ListHeaderComponent={
<View style={styles.header}>
<Text style={styles.heading} accessibilityRole="header">
My Reading List
</Text>
<Text style={styles.subtitle}>Find your next good read</Text>
</View>
}
ItemSeparatorComponent={() => <View style={styles.separator} />}
ListEmptyComponent={
<View style={styles.card}>
<Text style={styles.bookTitle}>Your reading list is empty</Text>
<Text style={styles.author}>
Add a book to the books array to start your list.
</Text>
</View>
}
/>
</SafeAreaView>
);
}

const styles = StyleSheet.create({
screen: { flex: 1, backgroundColor: '#f1f5f9' },
content: { padding: 16 },
separator: { height: 16 },
header: { gap: 6, marginBottom: 20 },
heading: { color: '#0f172a', fontSize: 28, fontWeight: '700' },
subtitle: { color: '#475569', fontSize: 16 },
card: {
padding: 16,
gap: 12,
backgroundColor: '#ffffff',
borderWidth: 1,
borderColor: '#cbd5e1',
borderRadius: 16,
},
bookRow: { flexDirection: 'row', alignItems: 'flex-start', gap: 12 },
bookIcon: { fontSize: 28, flexShrink: 0 },
details: { flex: 1, gap: 4 },
bookTitle: { color: '#0f172a', fontSize: 20, fontWeight: '600' },
author: { color: '#475569', fontSize: 16 },
status: {
alignSelf: 'flex-start',
maxWidth: '100%',
paddingHorizontal: 10,
paddingVertical: 6,
borderRadius: 8,
backgroundColor: '#e2e8f0',
color: '#334155',
fontSize: 14,
fontWeight: '600',
},
readStatus: { backgroundColor: '#dcfce7', color: '#166534' },
button: {
minHeight: 48,
padding: 12,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#1e40af',
borderRadius: 10,
},
buttonPressed: { backgroundColor: '#1e3a8a' },
buttonText: { color: '#ffffff', fontSize: 16, fontWeight: '600', textAlign: 'center' },
});

Follow the implementation​

  • Data: books supplies the entries. keyExtractor uses their IDs; renderItem passes each book’s text into the reusable card.
  • Interaction: BookCard still owns isRead. Pressing its button changes only that card’s status, colors, and action label. The press feedback and action-and-title accessibility label remain intact.
  • Layout: The safe-area container fills the screen. The list owns scrolling, and its content padding keeps cards away from the edges. A 16-unit separator replaces the previous gap between sibling cards; the header has its own bottom margin.
  • Long text: The details column keeps flex: 1, cards have no fixed height, and buttons have a minimum height so they can grow with text. Keep accessibility font scaling enabled.
  • Empty data: The heading remains visible, and ListEmptyComponent replaces the book rows with a useful message.

Save and look at your phone. You should see the familiar three cards. Mark The Hobbit as read, check the other two remain unread, then toggle it back. Scroll to the last button on a short screen. Try a long title and enlarged device text to check wrapping and reachability.

Try the empty state​

Temporarily replace only the data declaration with:

const books: Book[] = [];

Keep the Book type and the rest of the screen. Save: the heading and empty-state card should appear, with no book buttons. Restore the original array to bring back the three cards. This source edit is a learning check, not an in-app add/remove feature; returning cards may start unread again.

Fix common mistakes​

If you see…Check this
A missing or duplicate key warningGive every entry a unique, stable ID and use it in key or keyExtractor.
Status seems to follow a position after reorderingAvoid array-index keys for changing collections.
State resets on every parent renderDo not generate keys with Math.random() during rendering.
A mapped list displays nothingWith book => { ... }, explicitly return the JSX, or use the demonstrated parentheses.
BookCard cannot read keyReact consumes that special attribute; pass a separate ID prop if the card needs it.
A zero appears, or native text rendering failsUse count > 0 && ... rather than count && ....
A nested virtualized-list warningRemove the surrounding same-direction ScrollView; put the heading in ListHeaderComponent.
State is lost after a card is unmountedStable keys are not storage. Review the state-lifetime note above.
No empty message appearsSupply an empty array as data and set ListEmptyComponent.

Practice​

  1. Add a fourth book. Add one object with a unique ID. Check its title, author, and button label without adding another manual BookCard element.
  2. Change the status message. Show a different sentence for read and unread books. Choose a ternary or if, and keep a clear label in both states. Verify each button still describes its next action.
  3. Personalize the empty state. Change its heading and guidance, temporarily empty the array, and check the result on a narrow screen. Restore the books afterward.

Check your understanding​

  1. How does a book’s ID differ from its array index?
  2. What does renderItem receive, and what should it return?
  3. How does a ternary differ from isRead && <Text>Read</Text>?
  4. Why is count > 0 && ... safer than count && ...?
  5. Does a stable key guarantee that a virtualized card remembers its state after unmounting?
Compare your answers

The ID stays with the book; the index is its current position. renderItem receives an object containing the current item and returns UI for it. A ternary chooses between two values; the boolean AND example shows a label only when true. Comparing the count yields a boolean instead of a possible raw zero. Stable keys help identify components across updates, but local state is lost when a component is unmounted.

You are ready to continue when: You can add a book through data, explain its key, choose conditional UI, and trigger a friendly empty state without rewriting the screen.

Return to the learning path for further resources.

Official references​