Hamburger Icon
  • Labs icon Lab
  • Core Tech
Labs

Guided: Integrate Tailwind CSS with React

This lab is a hands-on experience that teaches you how to integrate Tailwind CSS (v3.4.17) with your React projects to build modern, responsive UIs using utility-first classes. Explore dynamic styling techniques, master effective class merging with tailwind-merge, and learn how to create scalable, maintainable applications. It equips web developers with the essential skills to enhance their React apps with visually appealing, optimized interfaces.

Labs

Path Info

Level
Clock icon Beginner
Duration
Clock icon 42m
Published
Clock icon Feb 28, 2025

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Table of Contents

  1. Challenge

    Introduction

    Welcome to the Guided: Integrate Tailwind CSS with React lab. This lab is designed for web developers and learners who want to enhance their React applications by utilising Tailwind CSS for efficient and scalable styling. You will engage in hands-on exercises covering Tailwind configuration, applying utility classes, using dynamic styles, and merging utility classes effectively with tailwind merge.

    This lab will use Tailwind CSS version 3.4.17 to ensure consistency and maintain identical steps. Using a different or more recent version in the future could lead to variations in the instructions.

    By the end of this Code Lab, you'll be proficient in integrating Tailwind CSS into your React applications. You'll master utility-first styling to build modern, responsive, and dynamic UIs and learn to optimise class management using tailwind-merge. These skills will enable you to create visually appealing, maintainable, and scalable interfaces in React.

    Key Takeaways:

    • Master Tailwind CSS integration in React.
    • Learn utility-first styling for building modern UI components.
    • Apply responsive and dynamic styles using props or state.
    • Optimize class management with tailwind-merge. ### Prerequisites

    Foundational React Knowledge

    • Learners should have a basic understanding of JavaScript, including fundamental concepts like variables, functions, and ES6+ syntax.

    • Basic experience with React, including functional components and props, is recommended.

    Basic Tailwind CSS Experience

    • Learners should be familiar with basic CSS concepts and how CSS frameworks like Tailwind CSS work, including using Tailwind utility classes.

    Command-Line & IDE Experience

    • Learners should be able to run commands in the terminal.

    • Comfortable using an IDE such as VS Code, WebStorm, or any other text editor to work with React project files. ### Book Shop App

    A React Book Shop app has already been created for this lab. As you progress through the lab, you will configure and style the application.

    The following packages must be installed to integrate Tailwind CSS into your project. Although the packages have already been installed for this lab, you can easily install them using the command below:

    npm install -D [email protected] postcss autoprefixer

    Explanation
    • Tailwind CSS is a utility-first CSS framework that relies on PostCSS to process its directives and generate the final CSS.
    • PostCSS is a tool for transforming CSS with JavaScript plugins. It interprets your Tailwind directives (like @tailwind and @layer), ensures your styles are compiled correctly and can run other plugins in the pipeline.
    • Autoprefixer is a popular PostCSS plugin that automatically adds vendor prefixes (e.g., webkit-, moz-) to your CSS rules, helping to ensure compatibility across different browsers.
    • Installing these tools as dev dependencies keeps them separate from the production code, meaning they are used only during development and the build process.
    **`__solution` folder:**

    codes: The final code for each step is stored in the __solution/code folder. For instance, the final code for Step 2 is available in the __solution/code/Step02 directory.

    images: This folder contains images depicting the lab's final state. For example, __solution/images/Step02 contains images depicting the final state of Step 2.

  2. Challenge

    Generate Tailwind CSS Config Files

    In this step, you will initialize Tailwind CSS to generate its configuration file. This will lay the groundwork for your application using Tailwind’s utility classes. Navigate to the first Terminal and execute the npm command to run the development server.

    Solution

    Execute the following command in your first Terminal.

    npm run dev
    
    Next, navigate to the {{localhost}} URL in your browser to view the **React Book Shop** application. The application is currently missing styling, but this will be addressed as we progress through the steps in this lab.
    Explanation
    The command above initializes Tailwind CSS by creating a `tailwind.config.js` file. The `-p` flag generates a `postcss.config.js` file, setting up both Tailwind and PostCSS configurations for the project.
    
    You should see an output upon running the above command, as shown in the example response below. This indicates that the Tailwind CSS configuration has been set up, allowing you to customise the framework according to your project’s needs.
    Created Tailwind CSS config file: tailwind.config.js 
    Created PostCSS config file: postcss.config.js
    

    Double-click on the workspace folder on your FILETREE sidebar to view the newly created config files, if they don't appear there. Congratulations! You have successfully initialized Tailwind CSS and generated its configuration file in your project.

  3. Challenge

    Configure Tailwind CSS

    In this step, you will configure Tailwind CSS by modifying the Tailwind configuration file. This setup allows Tailwind’s utility classes to be recognized and applied to your application.

    Explanation

    The configuration above tells Tailwind CSS to scan your HTML and source files (.js, .jsx, .ts, and .tsx) for class names. Only the classes that appear in these files are generated, resulting in a smaller and more efficient final CSS bundle that is easier to maintain.

    • ./index.html: This line includes the root HTML file.

    • ./src/**/*.{js,jsx,ts,tsx}: This line instructs Tailwind to look into any files within the src directory (and its subdirectories) that have the extensions .js, .jsx, .ts, or .tsx.

    Explanation

    Including these directives enables Tailwind’s base styles, preconfigured components, and utility classes, ensuring that fundamental styling, consistent design patterns, and various reusable utilities are available throughout your application.

    • @tailwind base: This directive injects Tailwind's base styles into your project. These include a set of CSS resets and foundational styles that help ensure consistency across browsers.

    • @tailwind components: This directive adds Tailwind's pre-built component classes, which you can use to build common UI elements quickly.

    • @tailwind utilities: This directive fetches all of Tailwind's utility classes, allowing you to style your HTML elements efficiently.

    Navigate to the first **Terminal** and stop the current process by pressing Ctrl + C. Now, execute the npm command to run the development server again. The server is being restarted to apply the Tailwind CSS config changes added in this step.
    Solution

    Execute the following command in your first Terminal again.

    npm run dev
    
    Next, navigate to the {{localhost}} URL in your browser to view the application. You should see that the Tailwind CSS config changes have been applied to the page. **Congratulations!** Your project is now configured to use Tailwind CSS, and the styles will apply correctly to your components.
  4. Challenge

    Use Tailwind CSS in The React App

    In this step, you will style your React components using Tailwind CSS classes, focusing on base styles, utility classes and responsiveness.

    Explanation
    • text-2xl adjusts the heading to Tailwind’s 2XL font size.
    • font-bold sets the text to bold weight.
    • text-gray-500 gives the heading a grey colour.

    Combining these utility classes provides a clear, readable, and visually distinct heading in the Book Shop application. Now, navigate to the {{localhost}} URL in your browser to view the updated changes from the previous step.

    Explanation
    • text-2xl sets the base heading size for smaller screens.
    • md:text-3xl applies a 3xl font size on medium screens (and above), ensuring better readability as screen size increases.
    • lg:text-4xl applies a 4xl size on large screens for maximum impact.

    This responsive approach adapts the text size according to the user’s device, providing a consistent and user-friendly experience. Now, navigate to the {{localhost}} URL in your browser to view the updated changes from the previous step. Then, resize your browser window to see how the responsive heading adjusts as the width changes. Congratulations! You have successfully applied Tailwind CSS classes to style React components, focusing on base styles and responsiveness.

  5. Challenge

    Use Dynamic styles to style components

    In this step, dynamic styles will be applied to each book card so that featured books display a yellow background and border, while on-sale books display a red background and border. This change helps differentiate the two, as they currently share the same background and border. The Book component in the src/Book.jsx file generates the book card, and the list of books (including their data) can be found in the Books component in the src/Books.jsx file. Since this lab focuses on Tailwind CSS and its integration, the underlying React components have already been set up for this lab.

    Explanation
    • featuredStyles applies the yellow background and border (bg-yellow-100 and border-yellow-400) only when the featured prop is true. This visually highlights featured books.

    • saleStyles similarly applies a red background and border for on-sale books.

    • combining both styles in the className ensures the component is styled dynamically based on its props. This approach makes the component more flexible and easier to maintain.

    Navigate to the {{localhost}} URL in your browser to view the updated changes from the previous step. The featured book should have a yellow background and border, whereas the on-sale book should have a red one.

    Note that the On Sale label is still displayed in black instead of red. The next task will fix this issue.

    Explanation
    • Dynamic Class Issue: The original code in the src/Book.jsx file uses a dynamic class name (text-${redColor}-500). Since Tailwind scans your files during the build process, it won’t detect this dynamic string as text-red-500 class. As a result, the red text class is omitted from the final CSS.

    • Using the Safelist: Adding the text-red-500 class to the safelist key in the tailwind.config.js ensures that this class is always included in the final CSS build. This guarantees that the On Sale label appears in red.

    Best Practice: Although Tailwind CSS provides an option of the safelist key, replacing the dynamic text-${redColor}-500 with a static text-red-500 in the className is the best solution in many real-life scenarios. Now, go to the {{localhost}} URL in your browser, and the On Sale label should appear in red color now.

    Congratulations! You have successfully applied Dynamic styles to the React components.

  6. Challenge

    Use Tailwind merge to merge utility classes

    In this step, you will use the Tailwind merge utility function to efficiently merge Tailwind CSS classes in JSX without any style conflicts.

    Navigate to the {{localhost}} URL in your browser to view the book list. You'll notice that the background and border of the To Kill a Mockingbird card is yellow, even though the book is on sale. This is due to a conflict between multiple class names, which will be fixed in this step.

    Explanation

    The tailwind-merge package helps to merge multiple Tailwind utility class names into a single string. This prevents conflicts and duplicates, making your Tailwind-based styling more concise and easier to maintain.

    Explanation
    • Merging Classes: The twMerge function merges featuredStyles and saleStyles, ensuring that any conflicting classes are correctly resolved.

    • combinedStyles: The resulting combinedStyles class is applied to the div tag, making the component styling easier to manage, mainly when a book is featured and on sale. It ensures that a book marked as featured and on sale will display the correct combined styling.

    Now, navigate to {{localhost}} URL in your browser to view the updated book list. Notice that the border and background of the `To Kill a Mockingbird` card is now red, indicating that the tailwind-merge utility is successfully combining the relevant classes.

    Congratulations! You’ve successfully implemented the tailwind-merge utility and completed the lab.

Asmin Bhandari is a full stack developer with years of experience in designing, developing and testing many applications and web based systems.

What's a lab?

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Provided environment for hands-on practice

We will provide the credentials and environment necessary for you to practice right within your browser.

Guided walkthrough

Follow along with the author’s guided walkthrough and build something new in your provided environment!

Did you know?

On average, you retain 75% more of your learning if you get time for practice.