Start Your Project With React and Tailwind CSS

Beginner-friendly guide on how to set up React and Tailwind CSS.

Sharad Ghimire
Aug 25, 2020 · 6 min read
I created that 😎

React is one of the most important players in today’s modern web development. Due to its simplicity and better design, anyone can pick it up and start building something in a couple of days. Not only this, for an independent developer like myself, building a side project is a breeze. Being a JavaScript library, it even fits well together in the MERN stack allows us to create whole full stack side projects. However, integrating a better-designed CSS is still a problem (for me at least). Although there are a couple of better tools, libraries, and frameworks, they come with built-in design systems, and most of our development time is wasted in overriding their default styles.

This article is about one of the best CSS frameworks that I have used in my development career and how to integrate it with the React project so that we can build anything super fast 🚀.

What is Tailwind CSS?

Tailwind CSS is a highly customizable, low-level CSS framework that gives us all of the building blocks we need to build better designs. So, it is simply a utility first CSS framework. I got hooked into Tailwind CSS when I first find out that I do not have to write a lot of CSS to make my application look pretty. According to their official documentation:

If you're sick of fighting the framework, overriding unwanted styles, and battling specificity wars, Tailwind was made for you.

Apart from many other frameworks like Material UI and Bootstrap, with the tailwind, we do not get the default theme and their built-in library of components. Instead, tailwind just provides us the list of class name and features that makes it way easier to build UI fast. And the most important thing is how perfect it fits together with React and its componentized design.

For example, we can easily style a button with hover and active styles without leaving HTML

<button className="bg-green-400 hover:bg-green-800 text-white font-bold rounded py-2 px-4">Button</button>
Button created from above code

Some worth noting features of Tailwind CSS are:

  • It makes it way easier to build responsive designs.
  • It provides fully featured customization with built-in theming system
  • Forget about writing all those long class names.
  • In tailwind, we are simply using the same classes over and over again so it has benefits over CSS caching.

You can find more about tailwind on their official website at tailwindcss.com

Setup

Before adding tailwind CSS, we need to first create a react project first. Simply, bootstrap react project with its create-react-app and cd into it.

npx create-react-app count-it
cd count-it

There are two ways we can add tailwind to our React project:

Using tailwind via CDN

<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">

We can simply add the above link tag in public/index.html and easily used all the classes provided by tailwind. However, many features like customization, directives, and installing plugins are not available using CDN.

Installing tailwind via npm

npm i tailwindcss autoprefixer postcss-cli

So, what is autoprefixer and postcss-cli? Post CSS is a tool for transforming CSS with JavaScript. It gives CSS some superpower by adding features like mixins and variables. Autoprefixer is a post-processor adds and removes vendor prefixes like -webkit and -moz. More details on https://tailwindcss.com/docs/installation.

Now, we need to initialize tailwind’s configuration:

npx tailwind init tailwind.config.js # with zero configuration## or npx tailwind init tailwind.config.js --full # with all default configurationtouch postcss.config.js

After the above command, we have to files tailwind.config.js which contains all our default configuration and an empty postcss.config.js file.

If you are curious on what is the default configuration, you find can https://github.com/tailwindlabs/tailwindcss/blob/master/stubs/defaultConfig.stub.js

For making use of PostCSS to lint our CSS and adding that autoprefixer add following code in post CSS config file.

module.exports = {
plugins: [
require("tailwindcss")("./tailwind.config.js"),
require("autoprefixer")
]
}

Now we need to get all the goodies that come with the tailwind. Create a CSS file copy the code below:

/* For simplicity I have added this styles.css in root of the project */@tailwind base; /* For base styles (check out normalize.css)  */
@tailwind components; /* Simple reuseable components provided by tailwind */
@tailwind utilitiess; /* utility classes generated based on our tailwind.config.js */

Next, we need to configure our project to build our CSS styles each time we run our application:

"scripts": {
"start": "npm run watch:css && react-scripts start",
"watch:css": "postcss src/styles.css -o src/main.css"
},

Simply import that src/main.css (which is the compiled version of our tailwind CSS) in the root file of our React project.

import React from "react";
import ReactDOM from "react-dom";
// Import compiled version of tailwind
import './main.css';
import App from "./App";ReactDOM.render(<App />, document.getElementById("root"));

That’s it for tailwind setup. Let’s try to build a simple count it app we bootstrapped above.

Usage

Now let’s try to build a simplest React app.

import React from "react";const Counter = () => {
const [num, setNum] = React.useState(0);
const subtract = () => setNum(num - 1);
const add = () => setNum(num + 1);
return (
<>
<h1 className="text-5xl font-bold text-center">Count It</h1>
<div className="flex md:flex-row flex-col items-center justify-center">
<button
className="bg-green-400 hover:bg-green-800 text-white
font-bold rounded py-2 px-4 m-8"
onClick={subtract}
>
-
</button>
<span className="text-4xl">{num}</span>
<button
className="bg-green-400 hover:bg-green-800
text-white font-bold rounded py-2 px-4 m-8"
onClick={add}
>
+
</button>
</div>
</>
);
};
export default Counter;

In the above code, we created a simple Counter component. The major feature of this component is to increase and decrease the counter state. We added subtract and add click handler for each button we have and displayed that number.

Here is the explanation of the above CSS

<div className="flex md:flex-row flex-col items-center justify-center">
....
</div>
{/* Here, we used out flex system to layout out btns and number. The md: prefix allowed us to create responsive design. */}
<button className="bg-green-400 hover:bg-green-800 text-white font-bold rounded py-2 px-4 m-8" onClick={add}> + </button>
{/* We added a green shade for backgorund, and another more darker shade of green when button is hovered. We made text white, font bold, button rounded and gave some padding and margin to the button */}
<span className="text-4xl">{num}</span>
{/* We can give font size using text-4xl. Here 4xl is defined in tainwind.config.js */}
Responsive Count It App 😅

This is one of the simplest components that we could make using React. Now, let's add that component to our index.js file.

import React from "react";
import ReactDOM from "react-dom";
// Import compiled version of tailwind
import './main.css';
// import App from "./App";
// component we just created above
import Counter from "./Counter";
ReactDOM.render(<Counter />, document.getElementById("root"));

Conclusion

“Count it” is one of the simplest apps to showcase how we can use tailwind. For an idea bigger projects, we could add many components with their respective styles inside.

The Startup

Get smarter at building your thing. Join The Startup’s +787K followers.

Sign up for Top 10 Stories

By The Startup

Get smarter at building your thing. Subscribe to receive The Startup's top 10 most read stories — delivered straight into your inbox, once a week. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Sharad Ghimire

Written by

A graduate fullstack developer with love for open source. Find me at srdstacks.now.sh

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +787K followers.

Sharad Ghimire

Written by

A graduate fullstack developer with love for open source. Find me at srdstacks.now.sh

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +787K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store