Tips for integrating Tailwind CSS into Create React App using React

I recently started using tailwindcss with my react app. I tried to follow the guide from tailwindcss but encountered various issues and bugs along the way. If anyone has advice on how to successfully start a project using tailwind and react, I would appreciate hearing about your experience.

Thank you!

Answer №1

Those are great questions! In my personal experience, I have recently delved into utilizing React boilerplate projects. To kick things off, open up your terminal and input the following commands to initiate a new project.

#using NPX
npx create-react-app tailwindreact-app

#using NPM
npm init react-app tailwindreact-app

#using yarn 
yarn create react-app tailwindreact-app

Create-react-app serves as the established React building tool for setting up new React endeavors.

Navigate to your app directory

cd tailwindreact-app

Subsequently, install Tailwind CSS along with its prerequisites

#using npm
npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9

#using Yarn
yarn add tailwindcss@npm:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9 -D 

As Create React App does not yet support PostCSS 8, we must download the version of PostCSS7 that aligns with Tailwind CSS v2

Next on the agenda is setting up CRACO to configure Tailwindcss

#using npm
npm install @craco/craco

#using Yarn
yarn add @craco/craco

Inaugurate a CRACO configuration file in your primary directory, either manually or through this command:

touch craco.config.js

Add tailwindcss and autoprefixer as PostCSS plugins to your CRACO configuration file:

// craco.config.js
module.exports = {
  style: {
    postcss: {
      plugins: [
        require('tailwindcss'),
        require('autoprefixer'),
      ],
    },
  },
}

Adjust your app to employ craco for executing development and build scripts.

Access your package.json file and replace the contents within scripts with:

  "scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "react-scripts eject"
  }

Erect the default configurations scaffold:

npx tailwindcss init

This action generates a tailwind.config.js in the foundational directory of your project. This file encapsulates all default configurations of Tailwind. By including an optional --full flag, you can generate a configuration file stocked with all the defaults bundled with Tailwind.

Integrating Tailwind in your CSS

Inside your src folder, establish a subfolder named styles. This will serve as the home for all your stylings.

Within that folder, craft a tailwind.css alongside an index.css document.

The index.css file acts as the hub for importing tailwind’s fundamental styles and configurations while tailwind.css houses the compiled output of index.css.

Tailwind CSS components, utilities, and base styles

Append the subsequent content to your index.css file.

//index.css
@tailwind base;
@tailwind components;
@tailwind utilities;

``@tailwind' functions as a tailwind directive implemented to infuse default base styles, components, utilities, and bespoke configurations.

@tailwind base **injects Tailwind’s base styles, encompassing Normalize.css coupled with supplementary base styles.</p>
<p><code>@tailwind components
introduces any component—a concise reusable style such as buttons, form constituents, etc.—classes enlisted by plugins enumerated in your tailwind config file.

Beneath the component import resides where custom component classes can be appended—elements that should be loaded prior to the default utilities to give room for potential overrides by the utilities.

For instance:

.btn { ... }
.form-input { ... }

@tailwind utilities embeds all of Tailwind’s utility classes (including both default and customized ones), which are assembled based on your config file.

Below the utilities import lies where additional unique utilities can be incorporated that diverge from the out-of-the-box provisions proffered by Tailwind.

Illustrative snippet:

.bg-pattern-graph-paper { ... }
.skew-45 { ... }

Tailwind swaps out all these directives during the construction phase and replaces them with the generated CSS.

Configuring your app to assemble your CSS file When configuring your app to leverage CRACO for fabricating your styles every time you execute the npm start or yarn start command, amend your package.json file by reshaping the contents within scripts:

 "scripts": {
    "build:style": "tailwind build src/styles/index.css -o src/styles/tailwind.css",
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "react-scripts eject"
  },

To import your CSS into the application, navigate to your index.js file and include your Tailwind styles:

import './styles/tailwind.css';

Eradicate the index.css and app.css files lying in your project's root directory and expunge their corresponding import statements in the Index.js and App.js documents, respectively.

Your index.js file should resemble something akin to this:

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './styles/tailwind.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

That wraps it up. I trust my insights will prove beneficial to others.

Answer №2

My journey into tailwind began with a deep dive into the official documentation, which can be accessed here

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

The custom filter in AngularJS fails to activate when a click event occurs

I am trying to customize the filtering of my table data based on selected conditions from a dropdown menu. I have created an AngularJS custom filter and passed all the necessary parameters. The desired functionality is that if no conditions are selected, ...

Can JavaScript be used to upload a file directly to memory for processing before transferring it to the server?

I'm exploring the idea of using a JavaScript encryption library (not Java) to encrypt a file before sending it to the server. Is it feasible to perform this process on the client-side and then upload the encrypted file using JavaScript, storing it in ...

Utilizing the onclick event to call a function with multiple arguments within Template literals

How can I properly write a function with multiple arguments using JavaScript post ES6 template literals when called by an onclick event? Here is my code: function displayImg(imageUrl, gameName, gameSummary, gameYear, cardId) { cardId = cardId.toStrin ...

Sending a JSON Object to an API endpoint using the $.ajax method

While attempting to extract data from a form by clicking a button and sending it to a web method in my code behind, I am aiming to pass it as a JSON object, following what seems to be the convention. Below is the current code snippet that I have, but unfor ...

What's the most effective method for implementing dynamic navigation in NextJS using Firebase integration?

Excited to begin building a web app using NextJS and Google's Firebase. This app will have both an admin panel and a public site, with the ability for the admin to edit the navigation of the public site. I'm debating whether it's wise to fet ...

When the button onClick event is not functioning as expected in NextJS with TypeScript

After creating a login page with a button to sign in and hit an API, I encountered an issue where clicking the button does not trigger any action. I have checked the console log and no errors or responses are showing up. Could there be a mistake in my code ...

Caution: There is a conflict in DefinePlugin with conflicting values for 'process.env.NODE_ENV'

Whenever I attempt to run development mode, I keep encountering the warning mentioned in the title. Although this script functioned properly for a previous website, it now consistently triggers this warning. Below is my package.json configuration: { &qu ...

Utilizing a Jquery plugin for enhanced form validation with the inclusion of supplementary techniques

I am looking to integrate a jQuery plugin into my form validation process, specifically to ensure that only letters are allowed in the name section. If a user enters special characters or numbers, I want the form to display an error message. Additionally, ...

async.series: flexible number of functions

Hello everyone, I'm currently working with Node.js (Express) and MongoDB (mongooseJS). My goal is to create a series of async functions that query the database in the right order. Here is my question: How do I go about creating a variable number of a ...

Updating the rotation of a grandchild in Three.js Object3D

In my current project, I am attempting to make the grandchild of a rotated Object3D element face towards the camera using the lookAt() method. I have experimented with various approaches to achieve this. However, the source code for the Object3D.lookAt() ...

Transform a jQuery element into an HTML element

I'm facing a dilemma where I have a jQuery element that needs to be passed into a function that only works with HTML elements. How can I efficiently convert the jQuery element into an HTML element? ...

Optical Character Recognition (OCR) tool

Does anyone have recommendations for a JavaScript OCR API that can easily be accessed via JavaScript? I'm searching for an API similar to this: upload an image along with the desired result type (e.g. numbers, objects, text, mixed, etc) and receive t ...

Variations between <div/> and <div></div>

When using Ajax to load two divs, I discovered an interesting difference in the way they are written. If I write them like this: <div id="informCandidacyId"/> <div id="idDivFiles"/> Although both divs are being loaded, only one view is added ...

What is the process for customizing the default animation in the Dialog component?

Currently I am utilizing the Material UI framework and looking into modifying the default animation for a Dialog opening. Specifically, I would like the Dialog to appear from bottom to top when it opens up. Any suggestions on how this can be achieved? Ap ...

Obtain the computed style by utilizing setTimeout for effective functionality

I want to retrieve the calculated style (background-color) of a span element. Here's my HTML code, consisting of two label elements, each containing an input and a span: <label> <input type="radio" name="numbers" value="01" checked/> ...

What is the most efficient way to generate a pug file with a hashed resource name using Webpack 2.0?

Here is how my file structure looks: /public (files ignored by git) /src index.js /views index.pug server.js webpack.config.js index.pug <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link href="/publi ...

What is the best way to arrange the JSON data in React Native using the map function

I have a JSON format like this: { "name":"xyz", "age-group":"bb" } How can I resolve the issue with this JSON? Here's the code I'm currently using: const array = [{ "name":"xyz", &q ...

What is the best way to keep track of choices made in 'mat-list-option' while using 'cdk-virtual-scroll-viewport'?

I have been working on implementing mat-list-option within cdk-virtual-scroll-viewport in an Angular 14 project. I came across a demo project in Angular 11 that helped me set up this implementation. In the Angular 11 demo, scrolling functions perfectly an ...

Whenever I try to launch my React app using the `npm start` command in my command

After successfully creating a Simple React App and getting the happy hacking message on cmd, I encountered numerous errors when trying to run "npm start" on cmd. Despite multiple attempts at uninstalling and reinstalling node and npm, the issue persists. H ...

$scope.apply is triggering both "catch" and "then" handlers

I am trying to ensure that the content of a page in Angular 1.6.2 and UI router is only displayed once it has been confirmed on the server that the user has the appropriate role/permissions. It seems like without using $scope.apply(), the catch() function ...