Generate a table of numbers given the rows and columns.
This is a preview of the final result:
Our code is split into two parts: the form and the table. The form is used to get the number of rows and columns from the user. The table is used to display the generated table. We use the useState
hook to store the state of the form and the table. When the user clicks the submit button, we generate the table.
Before generating the table we do a check if the number of rows
and columns
is greater than 0
. If it is, we generate the table using generateTable
function. We also clear the table if the user changes the number of rows
or columns
. This is done by setting the table state to null
. We use the &&
(and) operator to conditionally render the table preview.
The table is generated using nested for
loops. The outer loop iterates over the rows and the inner loop iterates over the columns. We use the map
method to generate the rows and columns. The map
method returns an array of React elements. We use the key
prop to uniquely identify each element.
The
key
prop is required when rendering an array of elements.
Finally, we render the table using the tableHTML
state.
1export default function TableGenerator() {2 const [requiredRows, setRequiredRows] = useState(0);3 const [requiredColumns, setRequiredColumns] = useState(0);4 const [tableHTML, setTableHTML] = useState(null);5
6 const generateTable = () => {7 if (requiredRows !== 0 && requiredColumns !== 0) {8 setTableHTML(null);9
10 let rows = [];11
12 for (let row = 1; row <= requiredRows; row++) {13 let cells = [];14
15 for (let column = 1; column <= requiredColumns; column++) {16 cells.push(<td key={column}></td>);17 }18
19 rows.push(<tr key={row}>{cells}</tr>);20 }21
22 setTableHTML(<tbody>{rows}</tbody>);23 }24 };25
26 return (27 <div>28 <h2>Table Generator</h2>29 <label>Number of rows</label>30 <input31 type="number"32 value={requiredRows}33 min={1}34 onChange={(e) => setRequiredRows(Number(e.target.value))}35 />36 <label>Number of columns</label>37 <input38 type="number"39 value={requiredColumns}40 min={1}41 onChange={(e) => setRequiredColumns(Number(e.target.value))}42 />43 <button onClick={generateTable}>Submit</button>44 {tableHTML && (45 <>46 <h2>Table preview</h2>47 <table>{tableHTML}</table>48 </>49 )}50 </div>51 );52}
Sign up to get updates when I write something new. No spam ever.
Subscribe to my Newsletter