Post navigation

Tailwind

Tailwind CSS – what is it & how to use it with React?

I decided to try out Tailwind CSS recently on a side project, just to see what it’s like to work with as I’d heard so many people discussing it. ‘Tailwind’ consists of three separate parts – Tailwind CSS, Headless UI, and Tailwind UI. Tailwind CSS has been made to be used both with HTML and with React or Vue – in this post I’ll focus on the Tailwind React combination, only using Tailwind CSS, I’ll walk through building a very simple form using React, and then installing Tailwind CSS and using it for all the styling.

What is Tailwind css?

Tailwind CSS is a CSS framework. It’s free, you can install it using an npm command on one line, and then start using it straight from your html. It’s very quick to set up and pretty quick to learn too, providing a great way of theming a new website or app quickly.

What is Headless UI

Headless UI is a collection of un-styled components for React and/or Vue which have been built to work specifically with Tailwind CSS.

What is Tailwind UI?

Tailwind UI is a suite of components built to work directly out of the box with Tailwind CSS. It’s a suite of fully styled components already built and ready to use out of the box. If you are a Saas developer this can save you hours and hours of time. This package costs money, but from what I’ve seen the benefit quickly outweighs the price tag.


Using Tailwind CSS with React – install & configure

To get started I created a new React app and then installed Tailwind CSS and all it’s dependencies according to the documentation, which overall I found really clear. :

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

You should check here though as the version numbers in that will likely change soon. Continuing to follow the Tailwind CSS installation instructions on that page I also installed Craco :

npm install @craco/craco

I always run npm start between each step when I’m setting up a project, just to make sure that nothing fundamental is broken, and that the React app still loads ok.

Next I updated the package.json scripts as per the instructions, so that they look like this:

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

… created a craco.config.json file like this:

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

Finally I ran this command to create a tailwind.config.json file.

npx tailwindcss-cli@latest init

Using Tailwind CSS in React code

Now that we’ve finished setting up Tailwind CSS in the React app it’s time to start writing some code and designing the UI. I went straight into the first bit of documentation presented to me after set up – https://tailwindcss.com/docs/utility-first – and grabbed the html from there to use in the header of the Twitter utility app I’m building. I just changed the two bits of text and the logo (I’ve made a quick and dirty logo just for something to use here). It’s not that pretty is it?! But it tells us that Tailwind is working, because the styles have been applied…. and I didn’t have to write a single line of CSS to get there which is a great start! This is what the code is at this point :

import logo from "./img/twitter-tool-logo.png";
import "./App.css";

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <div className="p-6 max-w-sm mx-auto bg-white rounded-xl shadow-md flex items-center space-x-4">
          <div className="flex-shrink-0">
            <img className="h-12 w-12" 
    			src={logo} alt="Twitter Tools logo" />
          </div>
          <div>
            <div className="text-xl font-medium text-black">
              Twitter Tools
            </div>
            <p className="text-gray-500">
              Useful Twitter developer utility app
            </p>
          </div>
        </div>
      </header>
    </div>
  );
}

export default App;

… and this is what the website looks like :

Styling a React form using Tailwind css

Now I want to add a text input, a label, and a button. I’ll be using a standard input, label and button and applying classes from Tailwind CSS to style them. To style the input, I wanted to add a border, a margin, and some padding so I searched for ‘border’ in the Tailwind css documentation and found a full list of utility classes for applying different borders. Then I repeated that for ‘margin’ and ‘padding’ and added each class as I found something close to what I was imagining. Once I’d put them together this is what it looked like :

tailwind css react form

And this is what the code for that page looks like at this point:

<div className="App">
      <header className="App-header">
        <div className="p-6 max-w-sm mx-auto bg-white rounded-xl shadow-md flex items-center space-x-4">
          <div className="flex-shrink-0">
            <img className="h-12 w-12" src={logo} alt="Twitter Tools logo" />
          </div>
          <div>
            <div className="text-xl font-medium text-black">Twitter Tools</div>
            <p className="text-gray-500">
              Useful Twitter developer utility app
            </p>
          </div>
        </div>
      </header>

      <form onSubmit={handleSubmit}>
        <label>
          Name:
          <input
            type="text"
            value={name}
            onChange={handleChange}
            className="border-2 rounded-md p-2 m-3"
          />
        </label>

        <button className="btn btn-blue" type="submit">
          Button
        </button>
      </form>
    </div>

Take a look at the input from the code above :

detailed look at tailwind utility class styling an input

It contains a selection of utility classes that I picked out from the documentation, and applied them in turn until the input looked the way I wanted it to. In reality if I was building a form with many inputs I would then take those styles and use @apply in the associated css file so that I could then just apply this batch of properties in one go. If you now look at the button you can see I’ve already done just that, so the button code and css file look like this:

<button className="btn btn-blue" type="submit">
  Button
</button>

.btn {
  @apply font-semibold py-2 px-4 rounded-lg;
}
.btn-blue {
  @apply bg-blue-500 hover:bg-blue-700 text-white;
}

Finally I’ll add the normal handleSubmit and handleChange functions that we’d normally use in the form and will show a message after we submit the form.

import React, { useState } from "react";

import logo from "./img/twitter-tool-logo.png";
import "./App.css";

function App() {
  const [name, setName] = useState("");
  const [active, setActive] = useState(false);

  const handleChange = (event) => {
    setName(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log("Submitted the form.");
    //now show the thank you message
    setActive(true);
  };

  return (
    <div className="App">
      <header className="App-header">
        <div className="p-6 max-w-sm mx-auto bg-white rounded-xl shadow-md flex items-center space-x-4">
          <div className="flex-shrink-0">
            <img className="h-12 w-12" src={logo} alt="Twitter Tools logo" />
          </div>
          <div>
            <div className="text-xl font-medium text-black">Twitter Tools</div>
            <p className="text-gray-500">
              Useful Twitter developer utility app
            </p>
          </div>
        </div>
      </header>

      <form onSubmit={handleSubmit}>
        <label>
          Name:
          <input
            type="text"
            value={name}
            onChange={handleChange}
            className="border-2 rounded-md p-2 m-3"
          />
        </label>

        <button className="btn btn-blue" type="submit">
          Button
        </button>
      </form>

      <p className={active ? "font-sans visible" : "font-sans invisible"}>
        Thanks for submitting the form
      </p>
    </div>
  );
}

export default App;

Now you know how to install Tailwind CSS, how to use it within a React app and how to turn collection of Tailwind CSS styles into reusable styles in your project.