What is the equivalent of v-for in react?
Asked Answered
P

2

5

In vue I can duplicate one svg file several times like v-for="i in 5":key="i". How can I do it in React?

<svg v-for="i in 5":key="i"  width="36px" height="35px" viewBox="0 0 36 35" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <!-- Generator: Sketch 49.3 (51167) - http://www.bohemiancoding.com/sketch -->
    <title>Star</title>
    <desc>Created with Sketch.</desc>
    <defs></defs>
    <g id="Symbols" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <g id="Profile-nav" transform="translate(-11.000000, -4.000000)" fill="#F8E71C" stroke="none" stroke-width="2">
            <g id="Group-2" transform="translate(0.000000, -1.000000)">
                <polygon id="Star" points="29 32.8753882 19.595436 38 21.3915479 27.145898 13.7830957 19.4589803 24.297718 17.8753882 29 8 33.702282 17.8753882 44.2169043 19.4589803 36.6084521 27.145898 38.404564 38"></polygon>
            </g>
        </g>
    </g>
</svg>
Poikilothermic answered 12/1, 2021 at 21:17 Comment(1)
https://mcmap.net/q/45010/-loop-inside-react-jsxIntellectualism
C
8

You'd do it in a very similar way to how you'd create an array in JavaScript. One option would be to use Array.from with a length, and use the second parameter in the mapper function for the index, eg:

Array.from({ length: 5 }, (_, i) => (
  <svg key={i}>
    // ...
  </svg>
));

const App = () => (
  Array.from({ length: 5 }, (_, i) => (
    <svg key={i} width="36px" height="35px" viewBox="0 0 36 35" version="1.1" xmlns="http://www.w3.org/2000/svg">
        <title>Star</title>
    <desc>Created with Sketch.</desc>
    <defs></defs>
    <g id="Symbols" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <g id="Profile-nav" transform="translate(-11.000000, -4.000000)" fill="#F8E71C" stroke="none" stroke-width="2">
            <g id="Group-2" transform="translate(0.000000, -1.000000)">
                <polygon id="Star" points="29 32.8753882 19.595436 38 21.3915479 27.145898 13.7830957 19.4589803 24.297718 17.8753882 29 8 33.702282 17.8753882 44.2169043 19.4589803 36.6084521 27.145898 38.404564 38"></polygon>
            </g>
        </g>
    </g>
    </svg>
  ))
);

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
Charmian answered 12/1, 2021 at 21:21 Comment(0)
U
2

You could do it using `

[...Array(5)].map((_,i)=>{
           return  <svg key={i} ...>
                    ...
                 </svg>
  })

and replace kebab-case attributes by camelCase ones :

stroke-width ---> strokeWidth
fill-rule ---> fillRule
Upheld answered 12/1, 2021 at 21:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.