I want to add a random amount of characters before an element, repeat that element 20 times, with a diffrent amount of characters before each time. For example:
function App() { return ( <> Hello World! This is time {i} // I want to add a random amount of spaces before the h1 tags above. I also want to repeat that h1 tags 20 times with a different amount of spaces before each h1 tag </> ) }
An example of what I want to return is
Hello World! This is time 1
Hello World! This is time 2
Hello World! This is time 3
Hello World! This is time 4
………
Each with a diffrent amount of spaces.
Advertisement
Answer
function HeaderWithLeadingSpacing({ maxSpacing = 20, num }) { const rdn = Math.round(Math.random() * maxSpacing); const spacing = Array.from(Array(rdn), () => 'u00A0'); return ( <h1>{spacing}Hello World! This is number {num}</h1> ) } function App() { return Array.from(Array(20), (_, i) => ( <HeaderWithLeadingSpacing maxSpacing={10} num={i + 1} /> )); } ReactDOM.render(<App />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"></div>
If I have understood correctly, the above code should do the trick.