Simplify TailwindCSS with TailwindBox

jnoncode

jn

Posted on November 16, 2024

Simplify TailwindCSS with TailwindBox

TailwindCSS is powerful, but it can be hard to read. Writing conditional styles can also be a hassle. So I decided to create a lightweight and simple library to solve this problem.

TailwindBox

GitHub logo jnoncode / tailwindbox

Easily manage TailwindCSS styles with simple object-like structures

banner

๐Ÿ”ง Installation

Install TailwindBox via npm or yarn:

npm install tailwindbox
# or
yarn add tailwindbox
Enter fullscreen mode Exit fullscreen mode

๐Ÿš€ Usage

Here's a quick example of how to use TailwindBox:

import { tw } from "tailwindbox";

function App() {
  const isDarkMode = true;

  const styles = tw({
    base: "p-4 rounded-lg shadow-md",
    dark: { if: isDarkMode, classes: "bg-gray-800 text-white" },
    light: { if: !isDarkMode, classes: "bg-white text-black" },
  });

  return <div className={styles}>Hello, TailwindBox!</div>;
}

export default App;
Enter fullscreen mode Exit fullscreen mode
  • base: Always applies the base styles (p-4 rounded-lg shadow-md).
  • dark: Applies bg-gray-800 text-white only if isDarkMode is true.
  • light: Applies bg-white text-black only if isDarkMode is false.

๐ŸŒŸ Features

  • Object-Like Structure: Define TailwindCSS styles in an object-basedโ€ฆ

TailwindBox makes your TailwindCSS code cleaner and easier to manage. Here's a quick example of how to use TailwindBox:

import { useState } from "react";
import { tw } from "tailwindbox";

function App() {
  const [isOpened, setIsOpened] = useState(false);

  const styles = tw({
    base: "pt-2 text-center font-light",
    open: { if: isOpened, classes: "inline-block border-t p-7" },
    closed: { if: !isOpened, classes: "hidden" },
  });

  return (
    <div>
      <button
        onClick={() => setIsOpened((prev) => !prev)}>
        Toggle Content
      </button>
      <div className={styles}>Hello World!</div>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode
  • base: Always applies the base styles (pt-2 text-center font-light).
  • open: Applies inline-block border-t p-7 only if isOpened is true.
  • closed: Applies hidden only if isOpened is false.

Features

  • Object-Like Structure: Define TailwindCSS styles in an object-based format.
  • Conditional Classes: Apply classes dynamically based on your application's state.
  • Improved Readability: Simplify long and complex class strings.
  • Lightweight: A minimal library designed for TailwindCSS users.

It will be a great help when you develop with TailwindCSS. Try it out, and feel free to share your feedback anytime!

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
jnoncode
jn

Posted on November 16, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About