hilarl
hilarl

Reputation: 6880

Logic inside loop not working on ReactJs

The condition inside the loop does not seem to be called or is not functioning:

let events = eventData.map(( timelineEvent ) => {
      let directions;
      if (timelineEvent % 2 == 0) {
        directions = "direction-r";
      } else {
        directions = "direction-l"
      }
      return (
        <TimelineEvent 
          type = {timelineEvent.type}
          time = {timelineEvent.time}
          title = {timelineEvent.title}
          place = {timelineEvent.place}
          location = {timelineEvent.location}
          description = {timelineEvent.description}
          direction = {directions}>
          <div>gallery</div>
          <TimelineEditButton
            deleteClick={timelineEvent.id} 
            dataId={ timelineEvent.id}
            editClick={this.openPartial.bind(this, "editEventPartial")} />
        </TimelineEvent>
      );
    });

The data renders but for some reason the condition does not seem to have any affect. Any help? Thanks

Upvotes: 0

Views: 140

Answers (1)

Josh Beam
Josh Beam

Reputation: 19772

You're querying object properties on timelineEvent (for example, timelineEvent.type), but you're expecting to also be able to use the modulus operator on the object. The modulus operator should be used with a number. That's why your condition is not being met.

You can see that calling the modulus operator on an object and using the "un-strict" equality operator == will always result in false. Here's the output from my console, as an example:

output

Edit

If you need the index, do this:

let events = eventData.map((timelineEvent, i) => {
  if(i % 2 === 0) {
    // do something
  }

Upvotes: 1

Related Questions