0

I have a simple question. If I have 1 component that gets rendered whenever a variable called count=1. How would I make this dynamic so that the number of components that get rendered will always equal count? I could do the if, else if but that would be tediuous. I was thinking something more like a for loop maybe? Here is some code I would like to render n times. It is simply a single component as shown below.

    return(
        <div>
            <SensorComponent user={props.user} 
                            moisture={value} 
                            historicalData={recentHistoricalData}
                            allHistoricalData={allHistoricalData}  
                            userInformation={userInformation}
                            setUserInformation={setUserInformation}
                            componentDetails={props.componentDetails}
                            setComponentDetails={props.setComponentDetails}
                            />
        </div>
    )
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Justin Oberle
  • 502
  • 3
  • 22

2 Answers2

1

You can just make an array from the count and iterate over it.

Here is an example which I made for you.

https://codesandbox.io/s/fervent-curran-3oodk?file=/src/App.js

NOTE: this will create a new instance of an array on each re render, if you don't want that, you can always memoize your created array.

const arr = useMemo(() => new Array(count).fill(), [count]);

and then

{arr.map((_, index) => <Component key={index} />)}

And if you want different props for all these components, then you would want to create an array with the different props/values and iterate over that.

const [arr, setArr] = useState([]);
Sarmad Shah
  • 3,725
  • 1
  • 20
  • 42
1

I suggest having the data needed for the component in an array, then iterate that array to create the components needed. A good example of this is a list of items, you would create the <ul>../</ul> bit and inside iterate through the array to generate the `

  • ...
  • items. This is no different from what you want. So

    you'd define an array of objects for the data e.g.

    componentData = [{
      name: 'Name 1',
    }, {
      name: 'name 2'
    }]
    

    Then in your render function, have some code like:

    <ul>
      {
        componentData.map(data => <li>data.name</li>);
      }
    </ul>
    

    This will iterate through the componentData, creating a new component, configured with each individual data object, one per component.

    Mark Small
    • 394
    • 1
    • 5