Dilhan Bhagat
Dilhan Bhagat

Reputation: 488

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!!!!!

Upvotes: 0

Views: 1329

Answers (3)

Prathap Reddy
Prathap Reddy

Reputation: 1739

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>);

Upvotes: -1

Mertcan Seğmen
Mertcan Seğmen

Reputation: 933

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>
))}

Upvotes: 4

Nasser Abachi
Nasser Abachi

Reputation: 1496

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>);

Upvotes: 0

Related Questions