ME MYSELF
ME MYSELF

Reputation: 19

ReactJS: Nested loop rendering element in 2D without relying on array or object

I am trying to render out a 10 x 10 checkbox input form in JSX by relying on the setState() changes, as I intended to have user to be able to change the number of dimension to render the likes of 20x20 or 15x15. I have tried map(items => {}) and it is not working.

const [xCells, setXCells] = useState(10)
const [yCells, setYCells] = useState(10)
let arrX = Array.apply(null, { length: xCells }).map(Number.call, Number)
let arrY = Array.apply(null, { length: yCells }).map(Number.call, Number)
return (
  <div className="RestaurantSeating">
    {' '}
    {arrX.map(item => {
      arr.map(item => {
        return <input type="checkbox" />
      })
    })}{' '}
  </div>
)

Upvotes: 0

Views: 59

Answers (2)

nanobar
nanobar

Reputation: 66435

The main problem is that you're using curly braces in your map functions {} which mean you should explicitly write the return i.e. return arrY.map..., currently you are returning nothing (undefined). Or you can omit the braces to implicitly return the yCells map:

function MyComponent() {
  const [xCells, setXCells] = React.useState(10)
  const [yCells, setYCells] = React.useState(10)

  let arrX = Array.apply(null, { length: xCells }).map(Number.call, Number)
  let arrY = Array.apply(null, { length: yCells }).map(Number.call, Number)

  return (
    <div className="RestaurantSeating">
      {arrX.map(x => 
        <div key={x} className="row">
          {arrY.map(y =>
            <input key={y} type="checkbox" />
          )}
        </div>
      )}
    </div>
  )
}

ReactDOM.render(<MyComponent />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Upvotes: 1

PIG208
PIG208

Reputation: 2380

An alternative for this will be:

{new Array(xCells).fill(0).map(_ => {
    return (<div>
        {new Array(yCells).fill(0).map(_ => {
            return <input type="checkbox" />
        })}
    </div>)
})}

function Test(){
  const [xCells, setXCells] = React.useState(10);
  const [yCells, setYCells] = React.useState(10);
  return (
    <div className="RestaurantSeating">
      {' '}
      {new Array(xCells).fill(0).map(_ => {
        return (<div>
          {new Array(yCells).fill(0).map(_ => {
            return <input type="checkbox" />
          })}
        </div>)
      })}{' '}
    </div>
  )
}

ReactDOM.render(<Test />, document.querySelector("#app"))
<script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>

<div id="app"></div>

Upvotes: 1

Related Questions