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
You can checkout the official page of
Tailwindcss
LINKOR
Try This:
You can use
.map()
function to iterate the the values.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: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.