Home > database >  n-th child selector not working in react map render function
n-th child selector not working in react map render function

Time:11-24

I have a react component inside which I am rendering a list containing some data, one below the other. I wanted every alternate data entry to have a different background color so I decided to make use of nth-child selctor in CSS.

JSX Code to render a list of data

<div className={styles.tableBody}>
  {tableRowsData.filter(filterMatch).map((row, rowIdx) => (
    <div
      key={rowIdx}
      className={styles.tableRow}
    >
      <div className={styles.value}>{row.url}</div>
      <div className={styles.value}>{row.startTime}</div>
      <div className={styles.value}>{row.endTime}</div>
      <div className={styles.value}>{row.status}</div>
      <div className={styles.value}>{row.score}</div>
    </div>
  ))}
</div>

Outputs

CSS Trial 1

When I use the following CSS, I get the background color is white.

.tableBody:nth-child(odd) {
  background-color: var(--primary-red);
}

enter image description here

CSS Trial 2

When I use the following CSS, I get the background color is red.

.tableBody:nth-child(even) {
  background-color: var(--primary-red);
}

enter image description here

CSS Trial 3

When I use the following CSS, I get the background color is red. Instead of getting only the 2nd card with a red background color.

.tableBody:nth-child(2) {
  background-color: var(--primary-red);
}

enter image description here

CSS Trial 4

When I use the following CSS, I get the background color is red for every alternate card and for every even card's odd child.

.tableBody :nth-child(odd) {
  background-color: var(--primary-red);
}

enter image description here

Could someone please help me understand this behavior and how to achieve what I wanted to?

Desired Result

enter image description here

CodePudding user response:

.tableBody:nth-child(odd) matches .tableBody elements that are themselves the nth-child.

You only have one such element so it will always be the first (and odd) child.

If you want to select the elements with styles.tableRow inside it then you need to say so:

.tableBody > .tableRow:nth-child(odd)

(This assumes that the value of styles.tableRow is 'tableRow').

  • Related