Home > OS >  I'm mapping through a list of comments and I am returning a component. is there a way I could s
I'm mapping through a list of comments and I am returning a component. is there a way I could s

Time:09-18

I'm mapping through an array of comments and I am returning the same component that handles the data passed to it. It is kind of confusing because I can not tell which is odd or even and I need to style it based on that.

      <div className="comments">
        <h3>comments</h3>
        //here
        <Comment />
      </div>

if it were like this, I would have known what to do


      <div className="comments">
        <h3>comments</h3>
        <ul>
          <li>You look good!</li>
          <li>You are amazing!</li>
          <li>What  a wonderful project!</li>
          <li>Are you free tomorrow? let's cook.</li>
        </ul>
      </div>

CodePudding user response:

Using JS you need to loop through all li elements and as per their index order, you can style them. But you can do it using CSS in a more simpler way. I would recommend that.

li:nth-child(odd) {
    color: green;
}
li:nth-child(even) {
    color: blue;
}
<div className="comments">
    <h3>comments</h3>
    <ul>
      <li>You look good!</li>
      <li>You are amazing!</li>
      <li>What  a wonderful project!</li>
      <li>Are you free tomorrow? let's cook.</li>
    </ul>
  </div>

CodePudding user response:

If you want to style the list with respect to add/even.

li:nth-child(even) {        
    background-color: antiquewhite;
 }
li:nth-child(odd) {        
    background-color: red;
 }

CodePudding user response:

You can pass a prop into the component and use it to style it. For example:

const Comment = ({customClass, data}) =>{
  return (<div className = {customClass}> {data} </div>)
}
Const App = () =>{
//Example data Arr
const dataArr = ["hello", "bye"]
return (<div className="comments">
        <h3>comments</h3>
        {dataArr.map((data, idx) => <Comment
customClass = {idx % 2 === 0 ? "Custom Class" : ""} data={data} />}
      </div>)
}

However, you can also look at the <Comment/> component and see what html it returns, and style through css selectors like :nth-child()

li:nth-child(odd) {
    color: black;
}
li:nth-child(even) {
    color: red;
}

The latter is more peformant on browsers so I would attempt that first. If you need more fine grain control over determining the styles, you can try the former to attach custom class names

  • Related