I have 2 arrays which I want to render in a table.
const arr1 = ["item1","item2","item3","item4"] const arr2 = ["price1","price2","price3","price4"]
I would like to convert this as
<table> <tr> <td>item1</td> <td>price1</td> </tr> <tr> <td>item2</td> <td>price2</td> </tr> <tr> <td>item3</td> <td>price3</td> </tr> <tr> <td>item4</td> <td>price4</td> </tr> </table>
Note: The arrays are guaranteed to have the same length.
Can someone please suggest how this can be dynamically done in React.
Thanks
Advertisement
Answer
You can store all the rows in an array and then use it in the table
:
export default function App() { const arr1 = ["item1","item2","item3","item4"] const arr2 = ["price1","price2","price3","price4"] const rows = [] for (const [index, value] of arr1.entries()) { rows.push( <tr key={index}> <td>{value}</td> <td>{arr2[index]}</td> </tr> ) } return ( <div className="App"> <table> <tbody> {rows} </tbody> </table> </div> ); }