Generate a table of numbers given the rows and columns.

Generated table of 4 by 5 columns

  1. The user enters the number of rows and columns in a form.
  2. When the form is submitted, a table with the respective number of rows and columns will be generated.
  3. The table contains rows x columns cells, each containing a number sequence from 1 to (rows x columns).

Solution

There are two parts to this question: (1) accepting user input and (2) generating the table.

Accepting user input

Since the table should be created only when the "Submit" button is pressed, the updates are one-way. A simple <form> where the input values are stored entirely within the DOM is sufficient. It's also possible to track the input values with state or data binding (depending on UI framework), but we will need more state values, which is unnecessary.

By using <input type="number" min={1}>, we ensure only numbers can be entered and leverage HTML validation so that the minimum value of the fields is 1. That way we don't have to write our own validation.

We can listen for the form's SubmitEvent, obtain the FormData from the SubmitEvent, and extract the rows and columns value from the FormData. Remember to do a event.preventDefault() within the submit callback otherwise the form submission will result in a page reload.

Generating the table

Generating the table is pretty straightforward. Note that <tr> should be within a <tbody> and not directly within the <table>. The trickier part of table generation is the numbers within each table cell, which involves using a mathematical formula. The number sequence for each column depends on whether the column is an even or odd one, and they be defined using the following formula:

Test cases

Accessibility