简体   繁体   中英

How update dynamically the className according its content in Next.js?

I try to set color dynamically according the content, for example if the value is android the background should be green and when it is ios , it should be blue. I want to do this with a generic function for all the Next.js project (I use Tailwind CSS by the moment).

This is the generic function to get the specific color according the content (in this case tag of a post).

export function getColor(tag) {
  switch (tag) {
    case "android":
    case "androidx":
    case "espresso":
    case "retrofit":
      return "bg-green-500"
    case "ios":
    case "facebook":
      return "bg-blue-500"
    case "angular":
    case "java":
    case "javascript":
    case "javafx":
    case "hms":
      return "bg-red-500"
    case "kotlin":
      return "bg-purple-500"
    case "firebase":
      return "bg-yellow-500"
    case "swift":
    case "swiftui":
    case "ubuntu":
      return "bg-orange-500"
  }
  return "bg-gray-500"
}

And this is the way I set the className .

<span
  className={`text-white uppercase ${getColor(post.tags?.[0])} inline-flex items-center px-2 rounded text-sm font-semibold font-mono`}>
  {post.tags?.[0]}
</span>

Apparently this should works, but it doesn't. Even sometimes this works and sometimes not. Previously I had this function on each file where I need it and it works but this is not the idea. I want to have a generic function (separated file) for all the project.

What is the right way to handle this? There is another way to update the className? What's the best approach for this? Thank you very much.

it's more convenient to use clsx for dynamic classes, it will look like className={clsx('some-class', areThereData && 'some-other-class', getColor(...))} .

You can use console.log or the debugger statement to debug; probably when it doesn't work, you don't pass the correct value to the function

If it was working when the logic was included in the files, but not now, then it sounds like the file containing the logic is not included in the content setting for your tailwind.config.js .

Try updating the content setting to include the logic file so Tailwind knows to add those class names (eg bg-green-500 , bg-blue-500 etc) to its output css.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM