0

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>

7
  • Could you at least format your code properly please? Commented Nov 29, 2016 at 19:46
  • 1
    The {index} shouldn't even work at all. You only need the braces inside JSX code (the pseudo-HTML part). Commented Nov 29, 2016 at 19:51
  • if ({index}==0} is invalid. Did you mean if (index == 0)? Please format your code. Commented Nov 29, 2016 at 19:51
  • @tanjir No, it's wronger than that (and if index is guaranteed numeric, non-strict equality is fine). Commented Nov 29, 2016 at 19:57
  • @tanjir Because you can't use {} as the OP did in plain JS functions. If it's an JSX expression the entire expression is surrounded by{} as in the answers below. Commented Nov 29, 2016 at 20:15

3 Answers 3

1

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>
Sign up to request clarification or add additional context in comments.

Comments

1

You can either use a conditional operator as follows:

{index===0? 
    <div className="item active" key={index}><img src={image.url} class="case-image"/ ></div>
:
    <div className="item" key={index}><img src={image.url} class="case-image"/ ></div>
}

or a function like this :

{(()=> {     
       if(index===0){
           return(<div className="item active" key={index}><img src={image.url} class="case-image"/ ></div>);}
       else{
           return(<div className="item" key={index}><img src={image.url} class="case-image"/ ></div>);}             
       })()}

5 Comments

true, I just wanted to show how to use an if block within the render. :) Best option in this scenario is to use a ternary operator and add the class.
removed 'cooler'. I was just really happy when I had first learnt we can use if-else blocks within the render. Makes the code more readable. And you can always initialize an empty list inside the block and insert more than one div in case of if or else, and return the list. I've found that very useful in many instances.
I argue against using if statements in renders--it injects too much responsibility, and mixes layers of abstractions. I feel like you start needing that kind of complexity, it should be removed to either (a) an external function (in the class or not) or (b) a separate component altogether. YMMV.
Sometimes, it makes the code more easier to read. If it is possible to move into a separate component (b), that's definitely better, but I'm not fond of (a) invoking functions from within the render. I used to do it all the time, and end up with a ton lot of functions within the render. :/
It's refactoring like any other. Any time you have an inflection point like that it makes the JSX that much harder to read. For trivial stuff, like in this case, as long as it's limited only to the expression involved, I might let it through a code review, but only if other duplication is removed.
0

I'll throw another alternative into the hat, using classnames:

const divClass = classNames('item', { active: index === 0 })
...
<div className={divClass} key={index}>
  <img src={image.url} className="case-image" />
</div>

I prefer wrapping up calculations outside of tags, and de-duplicating as much as possible.

2 Comments

Would this need to be separated into a separate component where you pass index as a property?
@adam-beck No, but it could be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.