I am trying to create a quiz app which at the end of each round creates a table which contains the players score as well as the score of a set number of random players. Lets say the number of random players has been pre selected and is 4. How do I use the value of 4 from the useState to render the below HTML 4 times? I couldn't get for loop to work, maybe someone else can or has another idea?
function Players () {
return <><tbody>
<tr>
<td>{teamName}</td>
<td ></td>
<td>{score}</td>
</tr>
</tbody></>
}
CodePudding user response:
You can create an array of desired length using Array.from and fill it with the Players
component and then render the array.
function App() {
const [count, setCount] = useState(4);
return (
<div>
{Array.from({ length: count }, () => (
<Players />
))}
</div>
);
}
CodePudding user response:
you can use Array constructor to do this.
Code:
const [number, setNumber] = useState(4);
{
[...Array(number)].map((_, index) => (
<div className="" key={index}> Whatever needs to be repeatedly </div>
)
)
}