Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Increment number for every instance of an element in React

I hope I phrased this question clearly. I have a small recipe app, for the recipe method I want to dynamically add Step 1, Step 2, Step 3 etc. for each step that is passed through via props.

The recipe’s steps are passed through as an array of objects:

recipeMethod: Array(2)
0: {step_instructions: 'Boil Water'}
1: {step_instructions: 'Heat Oil'}
length: 2

I am trying to get this array to display as

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Step 1
Boil Water

Step 2
Heat Oil

And additionally steps would be added for any further recipe method objects. Currently I can just get the step_instructions to display but cannot get the dynamically incrementing steps (that should start at 1)

Here is the relevant code:

import './MethodStep.css'
import React from 'react'

let methodArray
function mapMethod() {
  return methodArray.map((item, idx) => (
    <React.Fragment key={idx}>
      <div className="method-step small-header"></div>
      <div className="method-text">{item.step_instructions}</div>
    </React.Fragment>
  ))
}

function MethodStep(props) {
  methodArray = props.recipeMethod || []
  return <div className="recipe-method-container">{mapMethod()}</div>
}

export default MethodStep

>Solution :

as @louys mentioned above you can easily achieve that using

Steps {idx + 1 }

Above will print the each index of methodArray after adding 1.

I also noticed you are using Index as key. This is wrong practice as key should be always unique. You can append some string with it to make it unique.

like below:

<React.Fragment key={step-${idx}}>

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading