OneBite.Dev - Coding blog in a bite size

use tailwind css in react

Code snippet for how to use tailwind css in react with sample and detail explanation

Utilizing Tailwind CSS in React can revolutionize your development experience by providing low-level utility classes to speed up your workflow. Tailwind being a utility-first CSS framework is highly composable, customizable, and scalable, making it a perfect pair for React.

Code Snippet: Setup Tailwind CSS in a React project

Let’s go through setting up Tailwind in a React project. The steps are quite straightforward. In this guide, we will use Create React App as our base project.

# Create a new React project
npx create-react-app my-app

# Move into the new React app
cd my-app

# Install Tailwind via npm
npm install tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9

# Create a new configuration file for Tailwind
npx tailwindcss init -p

After running these commands, import the generated Tailwind CSS file into your src/index.js file.

import './styles/index.css';

Additionally, in your src/styles/index.css file, inject Tailwind’s style directives.

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

Finally, build the final CSS using a script in your package.json:

"scripts": {
    "start": "npm run build:css && react-scripts start",
    "build": "npm run build:css && react-scripts build",
    "build:css": "postcss src/styles/index.css -o src/styles/tailwind.css"
  }

Code Explanation: Setup Tailwind CSS in a React project

In the beginning, we create a new React project using Create-React-App.

With our new React project established, we use npm to install Tailwind CSS, PostCSS, and Autoprefixer. It’s important to make sure that these are compatible versions to avoid any conflicts.

We then utilize the tailwindcss init -p command to create a new configuration file for Tailwind. This generates two files, tailwind.config.js and postcss.config.js. These are configuration files which you can adjust to suit your project’s needs.

Next, we import the generated Tailwind CSS file into our src/index.js file. This helps to ensure that the styles are available throughout our app.

The directives in the index.css file are ones that inject Tailwind’s styles into the stylesheet. ‘Base’ applies the default styles, ‘Components’ are for pre-styled elements, and ‘Utilities’ are for single purpose classes.

Lastly, we use the PostCSS CLI to process our CSS. This can be done manually, but automating it with a package.json script facilitates faster, easier builds. The start and build scripts ensure that every time we start or build our app, our CSS gets processed accordingly.

Now, you have fully integrated Tailwind CSS into your React project. You can start building your user interface with the power of Tailwind and React combined.

css