Iniubong Obonguko Frontend developer, Vue ninja, code enthusiast. Learning every day.

Styling SolidJS applications using Tailwind CSS

4 min read 1209

Introduction

Tailwind CSS has grown in popularity over the years, and has become the go-to CSS framework for web developers who want to quickly ship frontend user interfaces.

In this guide, we’ll go through how we can install and use Tailwind with SolidJS, a JavaScript framework that has been gaining popularity for its lightweight nature and blazing fast speeds.

SolidJS setup

To create a Solid JS application, run the following command on the terminal:

#javascript
npx degit solidjs/templates/js solid-tailwind
#typescript
npx degit solidjs/templates/ts solid-tailwind

The command above clones a SolidJS template application built with Vite. You can choose to clone either the TypeScript or JavaScript template version, but for this guide we’ll proceed with the JavaScript template.

To complete the setup, install the project dependencies. First, move into the newly created project folder using the cd command:

cd solid-tailwind

Then install the dependencies by running the following:

npm install
#OR 
yarn install

Next, you can view the created project by running a local server using this command:

npm run dev
#OR
yarn dev

The command above spins up a local development server on port 3000 if no other application is running on that port.

Go to http://localhost:3000/ to view the app running.

blank solidJS app

Tailwind setup

Next up, we’ll install and setup Tailwind to work with our newly created SolidJS project.

To setup Tailwind, we need to install it along with several other dependencies such as PostCSS and Autoprefixer.

Install the dependencies with the following command:

npm install -D [email protected] [email protected] [email protected]
#OR
yarn add -D [email protected] [email protected] [email protected]                 

Next, we need to generate our tailwind.config.js and postcss.config.js files. These files let us configure Tailwind and PostCSS to work as we want.

To generate these files and their content, run the following command:

npx tailwindcss init -p

Next, let’s update the purge array in our tailwind.config.js file to include a list of files or directories we want to remove unused Tailwind classes from. This is also known as treeshaking, and it helps to minimize our bundle size when we deploy our application:

#tailwind.config.js
module.exports = {
  purge: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

Now we’ll import Tailwind’s CSS styles in our index.css file, which is located in the src folder.

Empty its content and replace with the following code:

/* index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

The final step in setting up Tailwind is to import Tailwind into your index.jsx or index.ts (if you used the TypeScript template):

#index.jsx or index.ts
import { render } from "solid-js/web";
import "tailwindcss/tailwind.css";

import "./index.css";
import App from "./App";
render(App, document.getElementById("root"));

Let’s confirm our installation by adding Tailwind classes to the paragraph tags in our App.jsx or App.ts file:

<p class="text-4xl text-red-400 tracking-widest">
  Edit src/App.jsx and save to reload. </p>

Our app screen on the browser should now look like this:

blank SolidJS with tailwind app

Voilà, we’ve successfully installed Tailwind! Now we can use Tailwind classes in our HTML markup in our .jsx or .ts files to style our application as we desire.

Styling a SolidJS application with Tailwind

In this section, we’ll build and style a mini SolidJS application that makes an API call to the OpenBreweryDB API and fetches a list of breweries. We’ll style and display the output using Tailwind.

Our finished application should look like this:

List of breweries in a SolidJS Tailwind app

Let’s head into our App.jsx file to get started. First, delete its content and replace with the following code:

import { onMount, For } from "solid-js";
import { createSignal } from "solid-js";

function App() {
  const [breweryList, setBreweryList] = createSignal([]);
  const fetchBreweries = () => {
    const apiUrl = "https://api.openbrewerydb.org/breweries/";
    fetch(apiUrl)
      .then((response) => response.json())
      .then((data) => {
        console.log(data)
        setBreweryList(data)
      });
  }
  onMount(() => {
    fetchBreweries();
  })
  return (
    <div>
    </div>
  );
}
export default App;

The code above simply fetches the list of breweries from the API and sets it equal to the breweryList array when the application is first instantiated.

We’ve gotten the data, what’s next is to display the data onto the browser screen. To achieve this, let’s work on the HTML markup and style it.

First, we add Tailwind classes to the root div:

return (
    <div class="bg-blue-200 h-full"></div>
);

The bg-blue-200 class sets the background color of the root div to a certain shade of blue and the h-full class sets the height to 100 percent.

Next, we add our app title between h1 tags:

return (
  <div class="bg-blue-200 h-full">
    <h1 class="text-3xl text-red-400 text-center py-6">List of Breweries</h1>
  </div>
);

The text-3xl class increases the font size to 30px,
text-red-400 changes the text color to a certain shade of red, text-center centers the text and py-6 adds a padding of 24px to the top and bottom of the text.

Now we have our ul tags, which which wrap around our For loop tags, which iterate over the data from the API and display it between the li tag:

return (
  <div class="bg-blue-200 h-full">
    <h1 class="text-3xl text-red-400 text-center py-6">List of Breweries</h1>
      <ul class="container mx-auto pb-10 grid grid-cols-4 gap-10">
        <For each={breweryList()}>{(list) =>
          <li class="bg-white p-4">
            <span class="inline-block mb-2 text-lg font-bold">
              {list.name}
            </span>
            <span class="inline-block mb-2">
              Country: {list.country}
            </span>
            <span class="inline-block mb-2">
              City: {list.city}
            </span>
          </li>
        }
        </For>
      </ul>
  </div>
);

The container class sets the max-width of our div to the min-width of the current breakpoint. This is useful if you’d prefer to design for a fixed set of screen sizes instead of trying to accommodate a fully fluid viewport.



Let’s list some of the other Tailwind classes used and their functions:

  • mx-auto sets the margin of the left and right directions to auto
  • grid instantiates a CSS grid on the element
  • grid-cols-4 sets the number of columns the CSS grid should have. Here we specified the number four, so we get four columns
  • gap-10 adds a grid gap property to the CSS grid. We specified with the number 10 so it sets a gap of 40px
  • bg-white sets the background color of the element to white
  • inline-block sets the element’s display property to inline-block

This is a pretty basic application, but Tailwind has plenty of other classes that can be used to make it even more advanced. For more information on all available Tailwind classes and their uses check out the official documentation.

Conclusion

Congratulations, you’ve made it to the end of this guide! You can now set up Tailwind in your SolidJS application and apply Tailwind styling to it.

To make the application we built even better, go through the Tailwind official documentation and make it responsive, add transitions, and explore the other styling options Tailwind has to offer.

Is your frontend hogging your users' CPU?

As web frontends get increasingly complex, resource-greedy features demand more and more from the browser. If you’re interested in monitoring and tracking client-side CPU usage, memory usage, and more for all of your users in production, try LogRocket.https://logrocket.com/signup/

LogRocket is like a DVR for web and mobile apps, recording everything that happens in your web app or site. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.

Modernize how you debug web and mobile apps — .

Iniubong Obonguko Frontend developer, Vue ninja, code enthusiast. Learning every day.

Leave a Reply