How to use TailwindCSS utility classes with className prop in React

131 views Asked by At

I've created a template (boilerplate) repository for React that provides ESLint, Typescript, TailwindCSS and Jest testing, and is built using Webpack.

However, TailwindCSS utility classes do not work if used in className prop of react components.

They work only with @apply in .css files.

GitHub URL AvirukBasak/reactjs-template-app.

Example

src/components/App/index.tsx The children don't get styled with font-bold.

import React from 'react'
import { printHelloWorld } from '@/utils/script'

import background from '@/images/background.jpg'
import styles from './App.css'

const App = (): JSX.Element => {
  printHelloWorld()
  return (
    <div className={styles.app + ' font-bold'}>
      <h1>Demo App</h1>
      <p>This is a Paragraph</p>
      <img src={background} />
    </div>
  )
}

export default App
1

There are 1 answers

3
Kyle Xyian Dilbeck On

Tailwind uses a modular style so you must create css files modularly. To use TailwindCSS utility classes in your React components, you can create a styles object that includes the utility classes and then apply them using the className prop. This way, you can maintain the utility-first approach that TailwindCSS encourages.

This is how the import and use would look:

// src/components/App/index.tsx

import React from 'react';
import { printHelloWorld } from '@/utils/script';

import background from '@/images/background.jpg';
import styles from './App.module.css'; // Change the import to use a CSS module

const App = (): JSX.Element => {
  printHelloWorld();
  return (
    <div className={`${styles.app} font-bold`}>
      <h1 className=`text-2xl`>Demo App</h1>
      <p className=`text-gray-700`>This is a Paragraph</p>
      <img src={background} className="max-w-full" alt="Background" />
    </div>
  );
};

export default App;

Make sure that your project is configured to use CSS modules, and adjust the class names and styles according to your design requirements. This way, you can use TailwindCSS utility classes in React components without relying on the @apply directive. (usually, this just means name your CSS files with the .module.css extension.)

/* src/components/App/App.module.css */

.app {
  /* Your existing styles */
  background-color: #f8f8f8;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

/* Additional TailwindCSS utility classes */
.text-2xl {
  font-size: 1.5rem;
}

.text-gray-700 {
  color: #4a5568;
}