Search code examples
javascriptarraysreactjsapiantd

Looping ant design tag color in React Js


I use Ant Design and data which coming from API. I assume the data like this

data = [
  {
     name: "John",
     job: "Freelancer",
  },
  {
     name: 'Bob',
     job: 'UI Designer'
  },
  {
     name: 'Sam',
     job: 'CEO'
  },
  {
     name: 'Alex',
     job: 'Mobile Dev'
  },
  {
     name: 'Jess',
     job: 'Web Dev'
  },
];

I want to return the job with Tag from Ant Design which the tag has a different color

<Tag color="green">green</Tag>
<Tag color="cyan">cyan</Tag>

I have looped the data. but I don't know how to make the data have a different color tag

data.map((el) => {
//This example doesn't have color
  return <Tag>{el.job}</Tag>
})

How to achieve that ? And sorry i'm not good enough in English. I hope you understand what i mean Or you can visit code sandbox here


Solution

  • In your data, add a property something like tagColor for each object.

    data = [
        {
         name: "John",
         job: "Freelancer",
         tagColor: "red"
        },
        {
         name: 'Bob',
         job: 'UI Designer'
         tagColor: "green"
        },
        {
         name: 'Sam',
         job: 'CEO'
         tagColor: "blue"
        },
    ];
    

    Then in the loop, use that property to dynamically add colors. Like,

    data.map((el) => {
      return <Tag color={el.tagColor}>{el.job}</Tag>
    });
    

    Updated

    If the colors can be random, you can place all your colors in an array. And you can pick colors one by one using index or even a randomiser. Something like,

    const colors = ["red", "blue", "green"];
    data.map((el, i) => {
      return <Tag color={colors[(i%colors.length)]}>{el.job}</Tag>
    });
    

    It will pick colors in the array one by one based on index.