Home > Software engineering >  How to conditionaly add "class" in Reactjs
How to conditionaly add "class" in Reactjs

Time:11-17

I am working with Reactjs and i am using nextjs,Right now i am trying to integrate/fetch slider data,Problem is i want to add class "active" to first slide only,So i am trying to use {post.id},But how can i use condition(add "active" class where id="1") ?So how can i do this using loop/mapfunction ? Here is my current code

   <div className={`carousel-item ${post.id === 1 ? 'active' : ''}`}>
                                  <img src="img/blog-slider.png" className="d-block w-100" alt="..." />
                                  <div className="carousel-caption  d-md-block">
                                    <h5>MBG starts Their Journey</h5>
                                    <p>Along with collecting as much data and information as possible, completing their research, and making their plan, the MBG team has now begun to implement their plan in detail, and they are in the initial steps. With the completion of any step, the MBG team will inform you about the latest news and information</p>
                                  </div>
                                </div>

CodePudding user response:

You can simply do it in this way :

<div className={`carousel-item ${post.id == 1 ? 'active' : ''}`}>

CodePudding user response:

You can refer to this article or this one.

There's one on stackoverflow as well.

CodePudding user response:

Using index we can have a condition as below

<>
  <div className={`carousel-item ${index === 0 ? "active" : ""}`}></div>
</>;

or -as per the condition you mentioned

<>
  <div className={`carousel-item ${post.id == 1 ? "active" : ""}`}></div>
</>;

CodePudding user response:

{this.state.trending.map((post, index) => {
var dt = post.CreatedAt;
  return (
           <>
           <div className={post.id == ‘1’ ? ‘carousel-item’ : ‘’>
           </>
          )
         })}

For more information checkout

ternary operator

  • Related