Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

.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').

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading