Getting Started With React + TypeScript + Tailwind + Classnames In Minutes
Published: Jul 25, 2020
Last updated: Jul 25, 2020
In this morning quick start, we are going to bootstrap a create-react-app with Tailwind and see how you can get it all up and running quickly with some state-based styling using classnames.
Installation
First, we need to create the TypeScript React app with create-react-app.
Second, we will install the other packages required for today.
# Create the app
npx create-react-app hello-tailwind --template typescript
# Change into our new app
cd hello-tailwind
# Using Yarn
yarn add tailwindcss classnames @types/classnames
Updating package.json
This part took quick inspiration from Dave Ceddia's post with a modern update.
Let's update our scripts to have the following:
{
"scripts": {
"build:tailwind": "tailwindcss build src/index.css -o src/tailwind.output.css",
"prestart": "npm run build:tailwind",
"prebuild": "npm run build:tailwind"
}
}
prestart and prebuild scripts will run before any start and build script that is run. We are telling it to build the index.css file and output it to src/tailwind.output.css.
Then, we will need to update our index.tsx file to change the import from index.css to tailwind.output.css:
import React from "react";
import ReactDOM from "react-dom";
import "./tailwind.output.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
Now we are ready to run!
Playing around with App.tsx
Run yarn start to get our application up and running.
Once up, let's update our App.tsx file to look like the following:
While this example is trivial, it becomes important for when you are defining variants based on props. We could swap out toggle to be logic such as status === 'error', etc. to reflect different possibilities through our application.
Conclusion
This has been a quick morning coffee and blog post on getting up and running with Tailwind without getting into the nitty gritty details.
Tailwind has a great reputation and for good reason - I highly recommend using this playground to try out what else it does offer.