SeaWarrior404
SeaWarrior404

Reputation: 4157

React JS: How to add classname for react component based on the position in an array?

I have a set of tooltips which are rendered from an array. I want to apply classname to the tooltip dynamically. For ex, If total number of items in the array = 20, then I want to apply className of 'left' for the first 5 elements in the array and className 'right' for the items 16-20. The number of items in the array are dynamic, so irrespective of N(Array items) I want to add classnames for only the first 5 elements and last 5 elements. How can I conditionally render them inside the render method of React?

Upvotes: 0

Views: 242

Answers (1)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Try some thing like this. Check for index arg in map function

const data = new Array(20).fill(0); // items

data.map((item, index, arr) => {
  let className = '';
  if (index < 5) {
    className = "left";
  } else if (arr.length > 5 && index >= arr.length - 5) {
    className = "right";
  }
  return <div className={className}> </div>
})

Upvotes: 1

Related Questions