Streamlining Tailwind CSS styles in your React/Next.js components for maximum efficiency

Since implementing Tailwind CSS in my React/Next.js project, I've noticed a decrease in maintainability compared to using traditional CSS or styled-components. Previously, I could easily consolidate style changes, but now I find myself duplicating classes for similar styling as shown below:

<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'>three</p>
</div>

This duplication of code makes it challenging to consistently update styles across the project. What are the recommended practices for utilizing Tailwind CSS in React/Next.js to maintain a centralized source of truth for styling, akin to traditional CSS or styled-components?

I'm striving to improve the cleanliness and maintainability of my code while harnessing the capabilities of Tailwind CSS. Any insights or examples would be greatly valued. Thank you!

Answer №1

To enhance the dryness of Tailwind, consider integrating class-variance-authority (cva). Find more information about cva here. cva enables the creation of diverse variants of a component based on specific needs. For instance:

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 introduce additional variants like border, shadow, etc. as per your requirements. Explore clsx and tailwind-merge along with cva for optimizing the dryness of your components with tailwind CSS and React/Next js.

Answer №2

It seems like I can relate to what you're feeling.

I have come up with 2 straightforward solutions:

  1. If you are working with React and notice repetitive elements in your code with similar classes each time, consider creating a component. For example, you could define a const Paragraph = (text) => {text}

Alternatively,

  1. Try using Tailwind @apply. If you enjoy crafting your own CSS classes, this approach may feel more intuitive to you.

In your CSS file:

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
   .p-custom {
     @apply text-[16px] text-red-700;
   }
}

Take a look at: https://tailwindcss.com/docs/reusing-styles#extracting-classes-with-apply

And also at: https://tailwindcss.com/docs/functions-and-directives#layer

I hope this information proves useful to you.

Answer №3

Make sure to visit the official Tailwindcss page for more information HERE

OR

Give this a shot:

To loop through values, you can utilize the .map() function.

const classes = "text-[16px] text-red-700";

const arr = ["one", "two", "three"];
<div>
{
arr.map(text=> (
<p className={classes} key={text} >{text}</p>
 ))
}
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to set up my React Application to run in Jenkins prior to executing Cypress tests?

Running Cypress in Jenkins requires the React application to be executed beforehand. However, while Jenkins is running the React application, it encounters the following error: Error from chokidar (/data/node_modules/@babel/runtime/regenerator): Error: EN ...

What is the process for embedding a React component within an HTML string and then displaying it using dangerouslySetInnerHTML?

In my NextJs project, I'm dealing with an HTML string fetched from the server that represents a blog post and includes multiple <img> tags. Currently, I render the post as follows: const blogpostHtml = "..." // HTML string from the server retur ...

Methods for resolving a ViewStyle typescript issue in react native

Trying to pass a width parameter into StyleSheet is causing an error like this: <View style={styles.children(width)}>{children}</View> Here's how I'm trying to use it: const styles = StyleSheet.create({ modalContent: { flex: ...

Is it possible to launch a React application with a specific Redux state preloaded?

Is there a way to skip navigating through a bulky frontend application in order to reach the specific component I want to modify? I'm curious if it's feasible to save the redux store and refresh my application after every code alteration using t ...

What steps should I take to resolve the 'buffer' issue in my jsonwebtoken?

As I am still new to ReactJS and the MERN stack in general, the code in Activate.js below essentially means that when the useEffect() hook is triggered, we will receive the jwt token extracted from the route parameter/url using the {match} props. This toke ...

Enable Sound when Hovering over Video in React Next.js

I am currently facing an issue while trying to incorporate a short video within my nextjs page using the HTML tag. The video starts off muted and I want it to play sound when hovered over. Despite my best efforts, I can't seem to get it working prope ...

Sorry, I am unable to provide rephrased content for error codes as they have

When attempting to build a React app and running the command: `npm run build` I encountered an error, even though everything was working fine up until today when I added some new UI components. This is the error message that appears when trying to run n ...

The compilation of SCSS CSS is encountering an error with the provided CSS code

Upon compiling SCSS, I encountered an error with the following CSS: span.icon-hcp { filter: progid: DXImageTransform.Microsoft.AlphaImageLoader(src='../images/icon-hc.jpg', sizingMethod='scale') !important; -ms-filter: ...

Encountering issues with vite build due to @types/react-router-dom package

I ran into an issue while developing my react app using Vite and TypeScript. Everything works fine when using Vite for development, but as soon as I switch to "tsc && vite build", I encounter numerous errors from @types/react-router-dom and @types/react-ro ...

Preventing background style from taking precedence over backgroundColor style in React's inline styling

What causes background to take precedence over backgroundColor in React inline-style? In this scenario, the lack of a specified green background-color results in the background gradient with transparency transitioning into white rather than green within t ...

The list fails to refresh after a new item is added and then returning to the page

I'm currently working on developing an application that enables coaches to create teams and monitor athletes. As part of this process, I am focusing on adding a new team to the system. The Dashboard.jsx file in my project calls the MyTeams Component, ...

What is the best way to monitor different selections to keep track of their state?

In a certain scenario, a user is presented with three options: They can select the body_type of a car, the car_year it was manufactured, or the car_make. Initially, there is a state called carJson which contains a list of cars. "2": { " ...

Error: Module not found - The file you are trying to import does not exist within the project directory

After upgrading to version 5.0.1 of react-scripts, I found myself needing to reintroduce support for Node.js core modules by incorporating the NodePolyfillPlugin in my react-scripts configuration and including it in the list of plugins. This successfully r ...

How can I show only the final four digits of an input field using Angular Material and AngularJS?

As a newcomer to Angular Material and Angular JS, I am striving to create an md-input field that displays only the last 4 digits in a masked format, such as "********1234". While my experience is currently limited to using md-input password fields where ...

Converting Background Images from html styling to Next.js

<div className="readyContent" style="background-image: url(assets/images/banner/banner-new.png);"> <div className="row w-100 align-items-center"> <div className="col-md-7 dFlex-center"> ...

The navbar tag is not functioning properly within Reactjs

Need help with creating a web header in ReactJS? I'm still learning Javascript and struggling to position the menu on the right side using bulma CSS. Can anyone offer some guidance? import React, { Component } from 'react'; import './H ...

Creating a wide-ranging megamenu with CSS only

I am interested in creating a full-width Mega menu. Here is the link for reference: http://codepen.io/tanmoy911/pen/KzjVdq My CSS code follows a 12 column grid system. .fui-navbar{list-style-type:none;margin:0;padding:0;overflow:hidden} .fui-navbar li{fl ...

Incorporating an Icon into the StackNavigator Bar to access the drawerNavigator in a react-native application

I've been attempting to include a menu type icon in the header of my stack navigator using the code below: import React, { Component } from 'react'; import { createStackNavigator, HeaderTitle } from '@react-navigation/stack'; impor ...

The server is failing to route the Django resource correctly, resulting in an error message "Failed to load resource: the server responded with a status of 404 (Not Found) main.7ec538f6.chunk.js:1"

During my web development project, I encountered an issue with serving React build files through Django. While the React build files were functioning correctly on their own, they were not being served properly by Django. This problem arose when changing ...

Tips for aligning text in an InputBase component from material-ui

I'm attempting to center the text area of an InputBase component from material-ui. I'm currently unsure if this is a bug or not. You can view an example of how I tried to center the text area here. Here is my code: import { InputBase, makeS ...