0

I'm trying to create a 5x5 table where each cell is a button, using React/JSX. The below throws an error in SandBox:

import "./styles.css";
import React from "react";

const makeCell = () => {
  return ( 
     <td>
       <button/>
     </td>
     )
};

const makeRow = () => {
  return( 
    <tr>
      {
        for (let=i; i<=5; i++){
          makeCell();
        }
      }
    </tr> 
  )
};

const makeTable = () => {
  return( 
    <table>
      {
        for (let=i; i<=5; i++){
          makeRow();
        }
      }
    </table> 
  )  
};

export default function App() {
  return (
    <div>
      <makeTable/>
    </div>
  );
}

/src/App.js: Unexpected token (16:8) 14 | 15 | { > 16 | for (let=i; i<=5; i++){ | ^ 17 | makeCell(); 18 | } 19 | } browser

Parsing error: Unexpected token 14 | 15 | { > 16 | for (let=i; i<=5; i++){ | ^ 17 | makeCell(); 18 | } 19 | } (null)

What is the easiest and most concise way to generate an ZxZ table in React? And could you explain why this approach isn't working?

jbuddy_13
  • 902
  • 2
  • 12
  • 34

1 Answers1

1

Codesandbox link: https://codesandbox.io/s/amazing-frog-c5h6hv?file=/src/App.js


export default function App() {
  return (
    <Table />
  );
}

const Table = () => {
  return (
    <table>
      <tbody>
        {Array(5)
          .fill(null)
          .map((_, index) => (
            <Row key={index} />
          ))}
      </tbody>
    </table>
  );
};

const Row = () => {
  return (
    <tr>
      {Array(5)
        .fill(null)
        .map((_, index) => (
          <Cell key={index} />
        ))}
    </tr>
  );
};


const Cell = () => {
  return (
    <td>
      <button>hello</button>
    </td>
  );
};


saidfurkandize
  • 216
  • 1
  • 8
  • So are for loops just not allowed in JSX? You have to get around them using array, map, etc – jbuddy_13 Apr 10 '22 at 20:05
  • 1
    You need to return JSX element. In your case you have multiple elements. . .map function returns an array which includes JSX elements. But you can also declare your items outside of return statements. Check out here: https://stackoverflow.com/questions/22876978/loop-inside-react-jsx – saidfurkandize Apr 10 '22 at 20:12