0

I'm looking to create a simple multiplication table using React. I've got the following code where I'm trying to loop through an array.

{array.map((num) => {
  return (
    <tr>
      <th>{num}</th>

      {array.map((x) => {
        return <td>{x}</td>;
      })}
    </tr>
  );
})}

I'm getting the error 'num.map is not a function'

I understand that num is not a function, but I wanted to check if there is a way I could basically create a nested loop? If not, my alternative would be to convert a string to JSX, but I wanted to check whether there's a way I could achieve this with map first.

1
  • 1
    num.map not not being call in the code you shared... Commented Feb 9, 2021 at 22:39

1 Answer 1

4

You can use Array.from() to create a range of numbers, iterate them, and produce react nodes:

const renderRange = (start, end, cb) => Array.from(
  { length: end - start + 1 },
  (_, i) => cb(i + start)
)

const Demo = () => (
  <table>
    <tbody>
      {renderRange(1, 10, x => (
        <tr key={x}>
          {renderRange(1, 10, y => (
            <td key={x * y}>
              {x * y}
            </td>
          ))}
        </tr>
      ))}
    </tbody>
  </table>
)

ReactDOM.render(
  <Demo />,
  root
)
td {
  border: 1px solid black;
  padding: 2px;
}
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.