This React Native example dynamically renders a set of TextInput fields based on a given guest count. It uses Array.from() to create an array of the desired length, and then iterates over it using .map() to generate corresponding components for each guest.

Why this is better:

  • Keeps rendering logic clean and isolated in a function.
  • Avoids modifying state in render methods (which was an issue in the original StackOverflow code).
  • Uses React’s key prop correctly to uniquely identify list items.
  • Fully compatible with React Native apps or Expo projects.

Complete Example Code:

import * as React from 'react';
import { View, Text, TextInput, StyleSheet, ScrollView } from 'react-native';

export default function App() {
const guestCount = 3; // dynamically change this value

// Generate input fields using map
const renderFields = () => {
return Array.from({ length: guestCount }, (_, index) => (
<View key={index} style={styles.row}>
<TextInput style={styles.input} placeholder="No" />
<TextInput style={styles.input} placeholder="Name" />
<TextInput style={styles.input} placeholder="Preference" />
</View>
));
};

return (
<ScrollView contentContainerStyle={styles.container}>
<Text style={styles.title}>Guest Details</Text>
<View style={styles.header}>
<Text style={styles.label}>No</Text>
<Text style={styles.label}>Name</Text>
<Text style={styles.label}>Preference</Text>
</View>
{renderFields()}
</ScrollView>
);
}

const styles = StyleSheet.create({
container: {
padding: 20,
},
title: {
fontSize: 24,
marginBottom: 20,
},
header: {
flexDirection: 'row',
marginBottom: 10,
},
label: {
flex: 1,
fontWeight: 'bold',
},
row: {
flexDirection: 'row',
marginBottom: 10,
},
input: {
flex: 1,
borderWidth: 1,
borderColor: '#ccc',
padding: 8,
marginRight: 5,
borderRadius: 5,
},
});

 

Need Help With React Native Development?

Work with our skilled React Native developers to accelerate your project and boost its performance.

Hire React Native Developers

Support On Demand!

Related Q&A