Gagan Gagan - 8 days ago 5
React JSX Question

if condition in reactjs

If condition is not working in reactjs. want to create a carousel so that its first image contains class "active" where as other do not.

Condition is the index is zero or not

how to apply if condition in react



class CaseImages extends React.Component {
constructor() {
super();
}

_getImages() {
return this.props.images.map((image, index) =>
if ({index}==0}<div className="item active" key={index}><img src={image.url} class="case-image"/ ></div>}
else{
<div className="item" key={index}><img src={image.url} class="case-image"/ ></div>
}
);
}
render(){
return(
<div className="row">
<div className="col-xs-12 col-sm-12">
<div className="case-feature-image">
<div id="myCarousel" className="carousel slide" data-ride="carousel">
<div className="carousel-inner" role="listbox">
{this._getImages()}
</div >
<a className ="left carousel-control" href ="#myCarousel" role ="data-slide = "prev">
<span className = "glyphicon glyphicon-chevron-left"
aria - hidden = "true"> </span>
<span className="sr-only">Previous</span>
</a>
<a className="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span className="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span className ="sr-only"> Next </span>
</a>
</div>
</div>
</div>
</div>
)
};
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>




Answer

Try something similar to the following:

<div className={index === 0 ? 'item active' : 'item'}>...</div>

You could also use a function to calculate the correct classes:

// this function needs to live *outside* of JSX
function getClasses(index) {
  return 'item' + index === 0 ? ' active' : '';
}

// this is in the JSX
<div className={getClasses(index)}>...</div>