Multi Dimensional Array in Tables
TEREN VELAN
Posted on October 17, 2021
Recently at work i was tasked to add styling to a table , but what was special was that because i needed to make the borders of my table rounded , i had to target the four corners of the table.
That's where multi dimensional arrays come in , Tables are always multi dimensional , from row first followed by columns. So this requires a nested for loop and conditional statement to accurately pint point the exact element in the loop i want to style. And with arrays come indexes which makes it so much easier.
We start by looping through the top level array to display the table's TR:
pages.map((row , rowIndex) => {
return (
<Tr>
</Tr>
)
}
Now that we have looped and displayed out
pages.map((row , rowIndex) => {
return (
<Tr>
{row.cell.map((cell , cellIndex) => {
return (
<Td></Td>
)
})
</Tr>
)
}
Now keep in mind that besides looping , we also need to pinpoint the
In pseudo code:
Top left corner of table: row[0][0]
This finds the first row , and the first column element for that row
Top right corner of table row[0][cell.length -1]
This finds the first row and the last column element of that row
*For example purposes i will only show the 2 corners of the table
so placing this in a conditional as part of our loop:
pages.map((row , rowIndex) => {
return (
<Tr>
{row.cell.map((cell , cellIndex) => {
if(rowIndex === 0 && cellIndex === 0){
return (
<Td backgroudColor="red"></Td>
)
}else if (
rowIndex === 0 &&
cellIndex === row.cell.length -1 ){
return (
<Td backgroudColor="yellow"></Td>
)
} else {
return (
<Td backgroudColor="white"></Td>
)
}
})
</Tr>
)
}
By setting a conditional to check if the index matches the index of the row and column element that we want , in this case the corners of the table, we will be able to manipulate the data and even styling in the table freely.
This is my first step into learning how to manipulate tables and as a front-end developer this is very important, please do share with me if you do it differently.
And today's also my birthday so just want to give a shout out to my mentor Ian for his patience and guidance in teaching me. Thanks Ian!
Posted on October 17, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024
November 30, 2024