skip to Main Content

I’ve been using Tailwind CSS in my React/Next.js project and have noticed that my code has become less maintainable compared to when I used traditional CSS or styled-components. In the past, I could easily centralize style changes, but now, I find myself repeating classes for similar styling, like this:

<div>
  <p className='text-[16px] text-red-700'>one</p>
  <p className='text-[16px] text-red-700'>two</p>
  <p className='text-[16px] text-red-700'>two</p>
</div>

This approach leads to code duplication and makes it harder to update styles consistently. What are the best practices for using Tailwind CSS in React/Next.js to maintain a single source of truth for styling, similar to how I used to do it with traditional CSS or styled-components?

I want to make my code cleaner and more maintainable while leveraging the power of Tailwind CSS. Any advice or examples would be greatly appreciated. Thanks!

2

Answers


  1. You can checkout the official page of Tailwindcss LINK

    OR

    Try This:

    You can use .map() function to iterate the the values.

    const classes = "text-[16px] text-red-700";
    
    const arr = ["one", "two", "three"];
    <div>
    {
    arr.map(text=> (
    <p className={classes} key={text} >{text}</p>
     ))
    }
    </div>
    
    
    Login or Signup to reply.
  2. Tailwind can be made DRY with class-variance-authority (cva). More about cva here.
    cva lets you create different variants of a component according to your use case. For example:

    import {cva} from "class-variance-authority"
    
    const para = cva(
        ["flex items-center"],
        {
          variants: {
            variant: {
              default: " text-gray-700 ",
              error: " text-red-700 ",
              success: " text-green-700 ",
            },
            size: {
              default: " text-[12px] ",
              md: " text-[14px] ",
              lg: " text-[16px] ",
            },
         },
         defaultVariants: {
           variant: "default",
           size: "default",
         },
    );
    
    
    ...
    
    
    para()
    // "flex items-center text-gray-700 text-[12px]"
    
    para({variant: "error", size: "md"});
    // "flex items-center text-red-700 text-[14px]"
    

    You can add other variants like border, shadow, etc. according to your use case. Also look for clsx and tailwind-merge in combination with cva for further drying up your components with tailwind CSS and React/Next js.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search