0

I want to repeat "★" as many times as a number in state in React.

What should I do?

I want to printing like this.

js ★★★
ts ★★
html ★★★

state = {
  myScores: [
    { name: "js", score: 3 },
    { name: "ts", score: 2 },
    { name: "html", score: 3 }
  ]
}

...

const myScores = this.state.myScores.map(
  ({name, score}) => (
    <div>
      {name}
      {
        for(let i=0; i<score; i++) {
          <div>★</div>
        }
      }
    </div>
  )
);
<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>
Jess2
  • 25
  • 5

1 Answers1

2

All you need to do is replace for loop with.

<div>{"★".repeat(score)}</div>

Reason why your code was not working the way you expected is.

  1. In practice the OP's code will throw an error since you cannot have JavaScript statements inside JSX (i.e. it won't render anything). very well explained by @FelixKling in comments.
  2. Since while iterating through for loop you're adding a new div every time which is a block element.so it will take up the complete width. you can read more about block elements here https://www.w3schools.com/html/html_blocks.asp
Code Maniac
  • 37,143
  • 5
  • 39
  • 60