I have an array populated with a list of random numbers e.g. array = [1,6,8,7,3,5,5,2,3,0]
I would like to render multiple copies of the same component, where the exact quantity is equal to each number in the array i.e. once, six times, eight times and so on, inside the DOM. Ideally each set of components would sit inside a <div />
in order to separate them, something like this:
<div><Drop /></div>
<div><Drop /> ... duplicated 5 more times </div>
<div><Drop /> ... duplicated 7 more times </div>
//... and so on
I found a useful line of code from this question: Array.from({ length: 5 }, (_, index) => <MyComponent key={index} />)
which works if I drop it straight into the render method, however if I put this into a function and try calling it for each number in the array
, setting the length to the item value, nothing is rendered in the DOM, also no errors.
Here is my code so far:
import {ReactComponent as Drop} from './images/raindrop.svg';
function App() {
// a static array for the sake of simplicity
const array = [1,6,8,7,3,5,5,2,3,0];
const Rain = () => {
array.forEach(getRain)
}
function getRain(rand) {
Array.from({ length: rand }, (_, index) => <Drop key={index} />)
}
return (
<div className="App">
<Rain />
</div>
);
export default App;
}
I haven't attempted to wrap anything in a <div />
yet but if you can see a simple way to also do this then much appreciated.
Thank you for your help.