gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
What's a better way to iterate through each enum and add them as text elements in tsx /…
- User
What's a better way to iterate through each enum and add them as text elements in tsx / react native
- Assistant
When you need to iterate through an enum and add them as text elements in a React Native component, you should use
mapinstead offorEach. TheforEachmethod doesn't return a new array, whereasmapdoes, which is suitable for rendering JSX elements. Here’s how you can rework your code accordingly:import React from 'react'; import { View, Text, StyleSheet } from 'react-native'; enum Tag { TAG_ONE = 'Tag One', TAG_TWO = 'Tag Two', TAG_THREE = 'Tag Three' } const MyComponent = () => { return ( <View style={styles.tagContainer}> {Object.keys(Tag).map((key, index) => ( <Text key={index} style={styles.tagText}> {Tag[key as keyof typeof Tag]} </Text> ))} </View> ); }; const styles = StyleSheet.create({ tagContainer: { flexDirection: 'row', flexWrap: 'wrap' }, tagText: { margin: 4, padding: 8, backgroundColor: 'lightgray', borderRadius: 4 } }); export default MyComponent;