Tailwind CSS Part II— ft. React

Dakota Chatt
11 min readDec 4, 2022

This article is the second in my Tailwind CSS series. If you haven’t read the first post, you can do so here:

https://medium.com/@dakotachatt/intro-to-tailwind-css-80514638b31b.

I explain what Tailwind CSS is as well as when you would or wouldn’t want to use it over another CSS framework like Bootstrap, or even your own custom CSS files. I also include a tutorial on basic Tailwind syntax that you can follow along with to get up to speed before continuing.

In this article, I will show you how to install Tailwind directly into your React projects instead of using the CDN script and will expand on some of Tailwind’s other features, including how to include your own custom configuration(s), layering directives and making your web pages mobile responsive.

Similar to the previous article, this series is primarily about how to integrate Tailwind CSS into your projects, and while this article will be using React as the front end framework when explaining or demo-ing code, I assume you have a working knowledge with React — and subsequently, HTML and CSS — and will not be going over any React concepts directly.

Why React?

React, which is a component based framework, is great to use with Tailwind. Since Tailwind CSS is similar in concept to inline styling, it can lead to a lot of repeated code when you have several elements (buttons, cards etc.) that have the same styling. With React we create custom components (styled primarily once) that can be reused anywhere in the application. Anytime we need to update the styling, we of course only have to update it in one place.

Before we dig in, there is one difference to note when using CSS classes with React vs. HTML that I want to make sure you know before continuing. With plain HTML, you would simply use “class” as the attribute to specify class names, however with React you must use “className” (due to class being a reserved word in javascript, which React uses to render HTML). We will be using the “className” variant for React in the remainder of this article.

//This is how you specify classes using plain HTML
<div class="text-xl">Here's Some Text</div>

//This is how you specify classes using HTML rendered with React
<div className="text-xl">Here's Some Text</div>

Installation

This section will walk you through the process of installing Tailwind CSS directly into your React project. While the public CDN used in the previous article can still be used in a React project, it is not recommended to do so for production level code due to possible decreased performance and security issues. Luckily, installing Tailwind in your project is quite straightforward.

Before you start, ensure you have Node.js installed as NPM will be used in the terminal to install Tailwind. If you do not have it installed, you can download it here: https://nodejs.org/en/. You can also use yarn if you’d like, but I will be using NPM.

Tailwind’s documentation is straight forward and we will be walking through the installation procedure step by step.

First we will need to create a new React Application. Open your terminal, and navigate to the directory you would like to save your React project in. Once your terminal shows the correct path, enter the following commands (one at a time), replacing “my-project” with the name of your project. The first command creates the React project and all the required dependencies (this may take a minute), and the second command navigates into the project folder afterward.

npx create-react-app my-project
cd my-project

Next we will be installing Tailwind into our newly created project by entering the following terminal commands (ensure you are in your new project’s directory). The first command installs Tailwind and its dependencies, while the second command generates the tailwind and postcss config files which we will talk about in the next section.

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

The next step is to open your new project in the IDE of your choice (I will be using VS Code). In your IDE, your file structure should now look something like the following:

Next we will go into the “tailwind.config.js” file (seen at the bottom of the screenshot above). You will see some pre-filled code in this file. The next step is to tell Tailwind what files and folders you want it to monitor. It will take this information and when it finds class names that it understands, it will be able to render them appropriately. The following string is inserted into the “content” field of the config file, and this string as written below tells Tailwind to look for javascript/typescript and jsx/tsx in the “src” folder of your project and to work its magic when it finds them. Note that this can be altered to look in different/multiple folders or file types (you can just have js, and jsx if you’re not using typescript anywhere in your project for example), however for this tutorial we will be using this value.

"./src/**/*.{js,jsx,ts,tsx}",

Your “tailwind.config.js” file should now look like this:

The final step to installation is adding the Tailwind directives to your index.css file. React includes some basic code in the files when you use create-react-app, so when you go to the index.css file in your src folder, you can just overwrite what is currently there with the following.

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

Your index.css file should now look like the following.

Now that Tailwind is installed and the defaults have been configured, we can test it to make sure it is working. Go to your app.js file, and replace the code that is in there with the following.

function App() {
return (
<div>
<h1>This is My Header</h1>
</div>
);
}

export default App;

Now you can run your React app by entering the following in the terminal (make sure you are still in your project’s directory):

npm start

After a few seconds your browser should load up and look like this:

If your page looks the same, great! You can move on and use Tailwind in your application.

If you notice that the above is styled any differently, you may have missed a step in the installation procedure. Since Tailwind strips all default styling of html components, the header element we added in app.js should not look any different than standard text.

Custom Configuration

Now that we have Tailwind installed and tested, we can talk about how to use your own custom configurations, and not be limited to the default Tailwind classes. Back in the previous article we looked at a way that you could specify a custom value simply by using square brackets appended to the end of the Tailwind class name (see below), but that can get cumbersome quickly if it needs to be done in multiple areas.

<button className="bg-[#2E4159]">Custom Background Color</button>

Using the “tailwind.config.js” file, it is possible to specify custom name value pairs in the “theme” section for each CSS selector that Tailwind supports, allowing you to call these custom values the same way as any Tailwind class without using square brackets, reducing your development overhead and making things easier to reference.

In this article we will be customizing our color palette beyond what Tailwind provides us by default. Note that the following steps can be applied to any CSS selector, and you can find more information in the Tailwind docs. https://tailwindcss.com/docs/configuration

When customizing colors, we have two options. Either we completely replace the default color palette Tailwind provides with colors of our own, or we can “extend” the default colors, and add new ones so you can use both.

We will create a button to illustrate this concept. In your app.js, overwrite the contents with the following, and you should see something like the image below:

function App() {
return (
<div>
<button className="bg-red-400 text-slate-100 p-2 m-4">
Customized Colors
</button>
</div>
);
}

export default App;

Let’s say we want to change the background to a specific shade of red that’s not part of the default Tailwind classes, #FF0000 for example. We will see what happens when we overwrite the default Tailwind colors in the tailwind.config.file first.

In your tailwind.config.js file you can add custom colors in the “theme” attribute. Take a look at the screenshot below for how to do so (you will need to add the “colors:” attribute object as shown, don’t forget the comma afterward).

Now let’s add this new “custom-red” color to the background of our button, replace your button code with the following, and your button should look like the image below:

<button className="bg-custom-red text-slate-100 p-2 m-4">
Customized Colors
</button>

So we can see our custom-red color now works, and we can reference it like any other Tailwind color, but you may have noticed that the text color is no longer the same, and is in fact the default black provided by the browser. This is because by putting our custom color where we did in the tailwind.config.js file, we effectively overwrote the pre-existing colors from Tailwind, and the “slate-100” color no longer exists in our project.

If we want to add our own custom colors while still being able to use Tailwind’s colors, we must instead put our “colors” attribute inside the “extend” attribute (and this goes for any other CSS selector property you want to customize). So if our tailwind.config.js file looks like the following instead, we should see our original text color as well as the new custom-red color we defined.

Layering Directives

Another optional feature we can use if we want to make our lives easier is changing the default styling of Tailwind’s “base layer”. This allows us to set certain default styling to specific HTML elements (like h1, button, etc.), which can reduce the code we need to type. This is especially useful if you’re using plain HTML. With React, this is less useful, as you can just make a component styled this way, however it’s still a useful feature to understand.

Say in our application, we know that we ALWAYS want our button to have a uniform padding value on all sides, for example 0.5rem, and rounded corners. Even though we can just use Tailwind’s p-2, and rounded-lg class names, we would have to type this EVERY time we styled a button element, and this only gets worse as the number of common styles increases.

Overwrite your app.js file with the updated code below. You can see that there are currently no padding or rounded corner styles applied.

function App() {
return (
<div>
<button className="bg-custom-red text-slate-100 m-4">
Changing Default Styling
</button>
</div>
);
}

export default App;

Now go to the index.css file in your src folder, and paste the following code, your index.css file should look like that below.

@layer base {
button {
@apply p-2;
@apply rounded-lg;
}
}

You should see that the button now has the padding and rounded corners that we specified. And if you were to make more buttons, they would also have the same padding and rounded corners without having to manually specify this in the button’s themselves.

You can apply the same logic to any HTML element, and you can specify as many elements and style defaults as you want (including custom ones from the previous section). In the example below, I’ve added default styles to an h1 and paragraph element as well.

Mobile Responsiveness and Breakpoints

With how prevalent mobile devices are in our lives, you need to always have mobile responsiveness in mind when you are designing your website. This can be done through media queries in traditional CSS, but Tailwind comes pre-loaded with classes that easily do this for you.

Tailwind uses prefixes from “sm:” up to “2xl:” to specify screen size breakpoints for styling. These are set by default to specific widths as shown below, but like most Tailwind classes, this can be overridden to any values if you need something different, though in most cases you won’t. Tailwind’s breakpoints work as the min-width property, which means, once the screen width gets to (at least) that specific value, the styles you associated with that breakpoint will apply. Note that for styling that applies to screens narrower than 640px, you don’t need to specify any breakpoint prefix.

See the docs for more information on responsive design with Tailwind. https://tailwindcss.com/docs/responsive-design

These are specified the same as any other Tailwind class in that you have to have one class for each style you want to apply for that breakpoint.

Let’s say we want to have the width of a div change based on the width of the screen. Let’s say we want it to take up 50% of the screen when the browser has a width of 1024px or more, 70% of the screen width at 640px or more, and 95% of the screen when the screen is less than 640px in width. Using the breakpoint specs in the previous image, you could write code something like the following (extra styling has been added to make things easier to see):

function App() {
return (
<div>
<div className="w-[95%] sm:w-[70%] lg:w-[50%] border-2 border-custom-red text-center mx-auto mt-10" >
Change the width of your browser!
</div>
</div>
);
}

export default App;

Now if you run the app, and resize your browser window you should see the following changes:

Screen width > 1024px (lg)
Screen width > 640px (sm)
Screen width < 640px (no prefix)

Now this is a simplistic example of course, but the logic can be applied to any Tailwind CSS class name like you would with any pseudo selector (like hover, active and so on), and once you get used to the work flow, making your page mobile responsive becomes a breeze.

Demo

In the following video I will walk you through a tutorial on making a basic mobile responsive portfolio landing page, where we will use each of the concepts we discussed in this article. While this tutorial is done with React, we won’t be getting into any complex React topics (aside from creating reusable components, and basic state management for mobile responsiveness) so the logic can apply to any other framework, and even plain HTML.

You can watch the video here in the event the embedded video doesn’t work: https://youtu.be/BvFD9O1I7MA

Resources:

Heroicons Installation Guide: https://github.com/tailwindlabs/heroicons
Tailwind Installation Guide: https://tailwindcss.com/docs/installation

--

--

Dakota Chatt
Dakota Chatt

Written by Dakota Chatt

Career Pivoter - Pivoting into software development

No responses yet