Hello, I’m Vuong, front end developer at AnyMind Group. In this article, I’d like to introduce how we combine Tailwindcss and Css-in-js using Twin in our latest Nextjs project called Popbox.
Tailwind CSS
A utility-first CSS framework packed with classes like flex, pt-4, text-center and rotate-90 that can be composed to build any design, directly in your markup.
It helps in building complex components from a constrained set of primitive utilities.
Styling a button by default:
<button>Save</button>
button {
padding: 32px;
margin: 16px;
font-weight: bold;
}
By using Tailwind CSS:
<button class='p-8 m-4 font-bold'>Save</button>
Twin macro
Twin.macro is a library that allows you to style your components using Tailwind CSS, and compiles them into supported CSS-inJS libaries. Giving us more power to style React components.
Twin Usage Examples
Using the tw
prop as an alternative to the default className
prop for passing Tailwind styles to an element.
Instead of styling a button using default className
like this:
import "twin.macro";
const Button = () => <button className="p-8 m-4 font-bold"> Save </button>;
You could write it this way:
import "twin.macro";
const Button = () => <button tw="p-8 m-4 font-bold"> Save </button>;
Twin also allows you write conditional styles like
import tw, { css } from "twin.macro";
import { useState } from "react";
const [disabled, setDisabled] = useState(true);
const Button = ({ disabled }) => (
<button css={[tw`p-8 m-4 font-bold`, disabled && tw`cursor-not-allowed`]} />
);
Using styled-components in Twin
import tw, { styled } from "twin.macro";
const Button = styled.div(({ disabled }: { disabled: boolean }) => [
tw`p-8 m-4 font-bold`,
disabled && tw`cursor-not-allowed`
]);
// Duplicating existing components
const PrimaryButton = tw(Button)`bg-blue`;
function App() {
return (
<>
<PrimaryButton>Save</PrimaryButton>
<Button>Cancel</Button>
</>
);
}
export default App;
Helpful suggestion from Twin
Twin.macro has a helpful suggestion if you write a wrong class it will show you something like:
✕ ml-7 was not found
Try one of these classes:
ml-0 [0] / ml-1 [0.25rem] / ml-2 [0.5rem] / ml-3 [0.75rem] / ml-4 [1rem] / ml-5 [1.25rem] / ml-6 [1.5rem]
ml-8 [2rem] / ml-10 [2.5rem] / ml-12 [3rem] / ml-16 [4rem] / ml-20 [5rem] / ml-24 [6rem] / ml-32 [8rem]
ml-40 [10rem] / ml-48 [12rem] / ml-56 [14rem] / ml-64 [16rem] / ml-auto [auto] / ml-px [1px]
In order to help you remember and write the correct class you need.
Conclusion
Tailwind classes can be quite long, and it causes some readability issues. Leading to maintenance problems. So it makes sense to combine Tailwind CSS and CSS-in-JS using Twin. Tailwind CSS handles the utility classes, and Styled Components keeps our component clean.
You can learn more form their official page TailwindCSS, Twin
Thank you and take care !