Code Eagle
Code Eagle

Reputation: 1242

how to create multiple elements in react where there is no array is available?

I am creating a Tic-Tac-toe game, so i need to create 9 empty squares, i have a ul and 9 lis each represent a square in the game, the problem is i have no array to loop through and create the lis as the tradition in react

   <ul className="squares">
        someArr.map((el, i) => {
           return <Square  props here/>
        })
   </ul>

const Square = (props) => {
  return <li {...props}></li>
}

Now i am forced to create all lis by hand and pass the props into each li and this looks too ugly!!

 <ul>
      <li className="square" ></li>
      <li className="square" ></li>
      <li className="square" ></li>
      <li className="square" ></li>
      <li className="square" ></li>
      <li className="square" ></li>
      <li className="square" ></li>
      <li className="square" ></li>
      <li className="square" ></li>
</ul>

Is there any way to achieve re-usability even when there is no array to create multiple elements?

Upvotes: 2

Views: 845

Answers (1)

palaѕн
palaѕн

Reputation: 73966

You can simply create an empty array of length 9 and then `map over it like:

[...Array(9)].map((_, i) => <li className="square" key={i}></li>)

Demo:

const Square = (props) => <li className="square"></li>

class App extends React.Component {
  render() {
    return (
      <ul>
        {[...Array(9)].map((_, i) => <Square key={i} />)}
      </ul>
    )
  }
}

ReactDOM.render(<App />, document.getElementById("app"));
.square{ width:50px;height:50px;background:skyblue; float:left; margin:5px;list-style-type:none;}
<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>

Upvotes: 2

Related Questions