简体   繁体   中英

Add numbers to list item React-native

I have a list of ingredients which I would like to add numbering to like....

Step 1... 1 ½ cups shredded Swiss cheese Step 2... 4 teaspoons all-purpose flour Step 3... ½ cup cooked ham, diced Step 4... 3 eggs

to differentiate each ingredient with Step numbering. I'm trying to make an algorithm to do this automatically. I've currently tried to map through each ingredient but I keep getting an error. I'm new to React Native and have a basic knowledge on Javascript this is probably easy but I just can't wrap my head around the way to do this.

This is my code

ingredients = [
    "1 ½ cups shredded Swiss cheese",
    '4 teaspoons all-purpose flour',
    '½ cup cooked ham, diced',
    '3 eggs',
    '1 cup milk'
]

const Ingridients = () => (
<View style={[styles.scene, { backgroundColor: 'white', height:'30%' }]}>
    {ingredients.map(ingri => <Text style={styles.ingredients} key={ingri}>{ingri.length}{ingri}</Text>)}
</View>);

I would really appreciate it from the bottom of my heart if someone could help me out to add numbering to this list. Thank you in advance!!!!!

You can get the current iteration's index with the second parameter that Array.map function provides

{ingredients.map((ingredient, index) => (
    <Text style={styles.ingredients} key={index}>
        {index + 1}: {ingredient}
    </Text>
))}

You can use the index of each element, Since javascript arrays are 0-indexed you can do something like this:

const Ingridients = () => (
<View style={[styles.scene, { backgroundColor: 'white', height:'30%' }]}>
    {ingredients.map( (ingri, index) =>  // <- introducing the index argument
<Text style={styles.ingredients} key={ingri}>
{'Step ' + (index+1) } // <- use the index + 1 since it starts with 0
{ingri.length}{ingri}
</Text>)}
</View>);

The Array map function provides current iteration index as second argument.

const Ingridients = () => (
<View style={[styles.scene, { backgroundColor: 'white', height:'30%' }]}>
    {ingredients.map((ingri, index) => <Text style={styles.ingredients} key={ingri}>Step {index + 1}. {ingri}</Text>)}
</View>);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM