Max RozenMax Rozen

Using Tailwind CSS with React and CSS-in-JS

Max Rozen
@RozenMD

If you've looked into adding Tailwind CSS to your React project, chances are you've seen the official installation guides, but what if you're already using Emotion, or styled-components?

Sure, you could probably try some funky combination of className and styled components such as:

const MyStyledDiv = styled.div`
color: red;
`;
const MyComponent = () => <MyStyledDiv className="mt-4 flex" />;

Assuming that would even work...

But what if you could use Tailwind classnames with your current CSS-in-JS configuration?

Introducing twin.macro

twin.macro by Ben Rogerson lets you write Tailwind CSS inside your CSS-in-JS, lints your Tailwind classnames, and doesn't make your bundle bigger.

twin.macro gives you access to a few things:

  • a tw prop on JSX elements:

    import 'twin.macro';
    const MyDiv = () => <div tw="border hover:border-black" />;
  • Tailwind class linting (this is the main reason I use this library):

    āœ• 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]
  • The standard Styled Component API:

    import tw from 'twin.macro';
    const MyDiv = tw.div`border hover:border-black`;
    // and cloning/styling other components
    const PurpleDiv = tw(MyDiv)`border-purple-500`;
  • The css prop:

    import tw from 'twin.macro';
    const Input = ({ hasHover }) => (
    <input css={[tw`border`, hasHover && tw`hover:border-black`]} />
    );

The library currently supports both Emotion and styled-components when using React, Preact, Create React App, Gatsby, Next.js, Snowpack, and more.

You'll want to see the Get started section of the README for instructions on how to install it for your particular combination of CSS-in-JS library and React framework.

Do you struggle to keep up with best practices in React?

I send a single email every two weeks with an article like this one, to help you keep track of what's happening in the React ecosystem.

Lots of developers like them, and I'd love to hear what you think as well. You can always unsubscribe.

    Join 1,508 React developers that have signed up so far!