Create tailwind css react components like styled components with classes name on multiple lines

Last update: Jun 21, 2022

Tailwind-Styled-Component

Create tailwind css react components like styled components with classes name on multiple lines

NPM version

Before 😬

">

  

After 🥳

">

<button class="flex bg-indigo-600">
    
button>

and

<Button $primary={false} />

Will be rendered as

">
<button class="flex bg-indigo-300">
    
button>

Be sure to set the entire class name

 Do ${p => p.$primary ? "bg-indigo-600" : "bg-indigo-300"}

 Don't bg-indigo-${p => p.$primary ? "600" : "300"}


Extends

const DefaultContainer = tw.div`
    flex
    items-center
`
const RedContainer = tw(DefaultContainer)`
    bg-red-300
`

Will be rendered as

">
<div class="flex items-center bg-red-300">
    
div>

Careful it does not overrides parent classes

Extends Styled Component

Extend styled components

const StyledComponentWithCustomCss = styled.div`
    filter: blur(1px);
`

const  = tw(StyledComponentWithCustomCss)`
   flex
`

Css rule filter is not supported by default on TailwindCSS

Will be rendered as

">
<div class="flex" style="filter: blur(1px);">
    
div>

Example

react component that renders an

which is // indigo and sized at 1.125rem interface TitleProps { $large: boolean; } const Title = tw.h1 ` ${(p) => (p.$large ? "text-lg" : "text-base")} text-indigo-500 ` // Create a react component that renders a
with // a special blue background color const SpecialBlueContainer = styled.section` background-color: #0366d6; ` // Create a react component that extends the SpecialBlueContainer to render // a tailwind
with the special blue background and adds the flex classes const Container = tw(SpecialBlueContainer)` flex items-center justify-center w-full ` // Use them like any other React component – except they're styled! render( Hello World, this is my first tailwind styled component! ) ">
import React from "react"
import tw from "tailwind-styled-components"
import styled from "styled-components"

// Create a  react component that renders an 

which is // indigo and sized at 1.125rem interface TitleProps { $large: boolean; } const Title = tw.h1<TitleProps>` ${(p) => (p.$large ? "text-lg" : "text-base")} text-indigo-500 ` // Create a react component that renders a
with // a special blue background color const SpecialBlueContainer = styled.section` background-color: #0366d6; ` // Create a react component that extends the SpecialBlueContainer to render // a tailwind
with the special blue background and adds the flex classes const Container = tw(SpecialBlueContainer)` flex items-center justify-center w-full ` // Use them like any other React component – except they're styled! render( <Container> <Title $large={true}>Hello World, this is my first tailwind styled component!</Title> </Container> )

GitHub

https://github.com/MathiasGilson/Tailwind-Styled-Component
Comments
  • 1. Received `true` for a non-boolean attribute `block`

    It seems like props are passed as an attribute and when I pass boolean, It throws error on the console. I am using next.js with typescript.

    This is the error

    Warning: Received `true` for a non-boolean attribute `block`.
    
    If you want to write it to the DOM, pass a string instead: block="true" or block={value.toString()}.
    button
    functionTemplate/</<@webpack-internal:///./node_modules/tailwind-styled-components/dist/tailwind.js:34:101
    

    Component looks like this

    import tw from 'tailwind-styled-components';
    
    interface Props {
      layout?: 'primary' | 'outline';
      disabled?: boolean;
      block?: boolean;
      size?: 'small' | 'medium' | 'large';
    }
    
    const Button = tw.button`
      flex justify-center items-center border border-solid font-medium rounded-sm transition-all duration-300 ease-in-out
    
      ${(props: Props) =>
        props.layout === 'primary' &&
        'border-primary-400 bg-primary-400 text-white hover:bg-primary-500 hover:border-primary-600'}
      ${(props: Props) =>
        props.layout === 'outline' &&
        'border-gray-300 text-gray-700 hover:border-blue-500 hover:text-blue-500'}
    
      ${(props: Props) =>
        props.disabled && 'bg-gray-50 border-gray-200 text-gray-200'}
        
      ${(props: Props) => props.size === 'small' && 'px-2 py-2 text-xs'}
      ${(props: Props) => props.size === 'medium' && 'px-4 py-3 text-xs'}
      ${(props: Props) => props.size === 'large' && 'px-5 py-4 text-lg'}
      
      ${(props: Props) => props.block && 'w-full'}
    `;
    
    export default Button;
    

    The workaround is using number as boolean block ? 1 : 0

    Reviewed by sethstha at 2021-03-27 07:48
  • 2. Input onChange and onFocus props are not working

    The props don't seems to be correctly propagated to the React Element.

    <Input onChange={console.log} onFocus={() => console.log(`focus`)} />
    
    const Input = tw.input``
    

    Check the example directory for a reproducible example

    Reviewed by MathiasGilson at 2021-05-02 14:42
  • 3. Failed to parse source map from '(...)/src/tailwind.tsx`

    Hi, first of all: Amazing Project! Thank you for building this!

    So, when I run npm start the console spits out: can't find src/ folder but still serves the react app correctly o.0

    WARNING in ./node_modules/tailwind-styled-components/dist/tailwind.js
    Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
    Failed to parse source map from '/Users/worker/development/hundertschaft-com/node_modules/tailwind-styled-components/src/tailwind.tsx' file: Error: ENOENT: no such file or directory, open '/Users/worker/development/hundertschaft-com/node_modules/tailwind-styled-components/src/tailwind.tsx'
     @ ./node_modules/tailwind-styled-components/dist/index.js 14:35-56
     @ ./src/App.tsx 7:0-44 9:19-24
     @ ./src/index.tsx 7:0-24 11:33-36
    
    3 warnings have detailed information that is not shown.
    Use 'stats.errorDetails: true' resp. '--stats-error-details' to show it.
    
    webpack 5.68.0 compiled with 3 warnings in 3036 ms
    No issues found.
    

    Not sure if simply publishing the src folder to npm would fix this.

    Reproduction

    • As Github Repo: https://github.com/D1no/reproduction-tailwind-styled-component
    • As Codesandbox: https://codesandbox.io/s/pensive-carson-y45qv?file=/src/App.tsx (resize the separator between browser and terminal in codesandbox to get back the full build log)

    Steps

    Thanks!

    Reviewed by D1no at 2022-02-04 19:13
  • 4. Typescript prop errors

    Running into some type issues but a basic button that has props passed through Button_tsx_—_template

    I'm using the default next.js typescript configuration

    {
      "compilerOptions": {
        "baseUrl": "src",
        "target": "es5",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noEmit": true,
        "esModuleInterop": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "jsx": "preserve"
      },
      "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
      "exclude": ["node_modules"]
    }
    
    Reviewed by kyh at 2021-09-04 02:36
  • 5. Using props does not work

    Given the following code

    const TimelineCurrent = tw.div<{ position: number }>`
      absolute
      left-0
      top-[0.575rem]
      ${(p) => `w-[calc(${p.position}%-0.75rem)]`}
      h-[0.35rem]
    `;
    

    it renders the following HTML

    <div position="100" class="absolute left-0 top-[0.575rem] w-[calc(100%-0.75rem)] h-[0.35rem]"></div>
    

    But the w-[calc(100%-0.75rem)] part is not picked up by Tailwind JIT, so it has no effect. Am I doing something wrong here?

    Reviewed by azzlack at 2022-03-30 07:43
  • 6. v2.1.1 Typescript error: Property '$as' is missing in type

    Hello. We have upgraded the package from 2.0.4 to 2.1.1 and received new typescript errors all over the codebase. Most of them indicate some kind of issue with the new $as prop. For example:

    src/components/Navigation/NavBar.tsx(225,12): error TS2769: No overload matches this call.
      Overload 1 of 2, '(props: { onClick?: MouseEventHandler<HTMLAnchorElement> | undefined; className?: string | undefined; color?: string | undefined; id?: string | undefined; ... 262 more ...; $active?: boolean | undefined; } & { ...; } & { ...; }): ReactElement<...>', gave the following error.
        Property '$as' is missing in type '{ children: TFunctionResult; onClick: () => void; }' but required in type '{ onClick?: MouseEventHandler<HTMLAnchorElement> | undefined; className?: string | undefined; color?: string | undefined; id?: string | undefined; ... 262 more ...; $active?: boolean | undefined; }'.
      Overload 2 of 2, '(props: StyledComponentPropsWithAs<TailwindComponent<Pick<Pick<ClassAttributes<HTMLAnchorElement> & AnchorHTMLAttributes<HTMLAnchorElement>, "key" | keyof AnchorHTMLAttributes<...>> & RefAttributes<...>, "key" | keyof AnchorHTMLAttributes<...>> & RefAttributes<...>>, ... 4 more ..., TailwindComponent<...>>): ReactElement<...>', gave the following error.
        Property '$as' is missing in type '{ children: TFunctionResult; onClick: () => void; }' but required in type '{ onClick?: MouseEventHandler<HTMLAnchorElement> | undefined; className?: string | undefined; color?: string | undefined; id?: string | undefined; ... 262 more ...; $active?: boolean | undefined; }'.
    

    The source code is as simple as follows:

    const LogInAnchor = tw.a`
      ...
    `
    const TwAnchor = tw(LogInAnchor)`
      ...
    `
    const Anchor = styled(TwAnchor)<{ $active?: boolean }>`
      ...
    `
    // later, error at the render site
    <Anchor>Logout</Anchor>
    

    By looking at the library's source code I couldn't understand why is the $as prop reported as missing, since it seems to be optional. Do you have any idea why this error occurs and how to fix it?

    Reviewed by simonasdev at 2022-01-19 19:36
  • 7. Tailwind Styled Components not working on Tailwind CSS v3

    I get the following error only when I try to use tailwind styled components:

    WARNING in ./node_modules/tailwind-styled-components/dist/domElements.js
    Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
    Failed to parse source map from '/home/amejia/code/projects/cryptopunks-clone/node_modules/tailwind-styled-components/src/domElements.ts' file: Error: ENOENT: no such file or directory, open '/home/amejia/code/projects/cryptopunks-clone/node_modules/tailwind-styled-components/src/domElements.ts'
     @ ./node_modules/tailwind-styled-components/dist/tailwind.js 15:38-62
     @ ./node_modules/tailwind-styled-components/dist/index.js 14:35-56
     @ ./src/App.js 6:0-44 21:16-22
     @ ./src/index.js 7:0-24 11:33-36
    
    WARNING in ./node_modules/tailwind-styled-components/dist/index.js
    Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
    Failed to parse source map from '/home/amejia/code/projects/cryptopunks-clone/node_modules/tailwind-styled-components/src/index.ts' file: Error: ENOENT: no such file or directory, open '/home/amejia/code/projects/cryptopunks-clone/node_modules/tailwind-styled-components/src/index.ts'
     @ ./src/App.js 6:0-44 21:16-22
     @ ./src/index.js 7:0-24 11:33-36
    
    WARNING in ./node_modules/tailwind-styled-components/dist/tailwind.js
    Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
    Failed to parse source map from '/home/amejia/code/projects/cryptopunks-clone/node_modules/tailwind-styled-components/src/tailwind.tsx' file: Error: ENOENT: no such file or directory, open '/home/amejia/code/projects/cryptopunks-clone/node_modules/tailwind-styled-components/src/tailwind.tsx'
     @ ./node_modules/tailwind-styled-components/dist/index.js 14:35-56
     @ ./src/App.js 6:0-44 21:16-22
     @ ./src/index.js 7:0-24 11:33-36
    
    3 warnings have detailed information that is not shown.
    Use 'stats.errorDetails: true' resp. '--stats-error-details' to show it.
    
    webpack 5.65.0 compiled with 3 warnings in 1682 ms
    

    I created my project following Tailwind CSS v3 documentation and Tailwind works fine in classNames, but whenever I try to use React Styled Components, although the styles are applied, the previous error pops up. bug

    Reviewed by 1ns4w at 2021-12-13 14:28
  • 8. TypeScript Error: This expression is not callable

    I'm getting the following TypeScript error when I use this package in a .tsx file. TS2349: This expression is not callable. Not all constituents of type 'FunctionTemplate | undefined' are callable. Type 'undefined' has no call signatures.

    • tsc version: 4.0.5
    • tailwind-styled-components version: 1.0.6

    TypeScript configuration:

    {
      "compilerOptions": {
        "target": "es5",
        "lib": [
          "dom",
          "dom.iterable",
          "esnext"
        ],
        "allowJs": true,
        "skipLibCheck": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noEmit": true,
        "esModuleInterop": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "jsx": "preserve",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true
      },
      "include": [
        "**/*.ts",
        "**/*.tsx"
      ],
      "exclude": [
        "./node_modules",
        "**/**/*.svg"
      ]
    }
    
    Reviewed by nickfla1 at 2020-12-17 19:53
  • 9. Feature: using tailwind-merge library to override parent classes

    Hi! First of all, this is a great library as it makes working with Tailwind a lot easier, and I'm very thankful for that.

    Like the documentation explains, this library doesn't override parent classes, it just concatenates the different classes and the result will depend on each case. Which brings to the following suggestion: how possible would it be to switch the use of the current library tailwindcss-classnames to tailwind-merge (https://github.com/dcastil/tailwind-merge) as this other library already handles tailwind classes overriding?

    I understand that this might be a breaking change given the current state of the library (if it's a hard change, but maybe it could be configurable?). However I believe users would benefit a lot more if it were possible to override parent classes.

    Thanks!

    Reviewed by bcucumber at 2022-03-20 18:05
  • 10. Feature: Expose css-like utility function known from styled-components

    First of all, trying this library, and loving it so far! 👏

    I was trying to structure my code and attempting to create shared styling between components that fundamentally do not share same functionally.

    To my knowledge; one could do this with styled components:

    import { css } from 'styled-components';
    
    const outlineStyle = css`
      outline-width: 2px;
      outline-style: 'solid';
      outline-color: 'orange';
    `
    // Button.tsx
    
    const Button = styled.button`
      ${outlineStyle}
    `
    
    const Input = styled.input`
      ${outlineStyle}
    `
    

    Basically, I think a wrapper css-function exported from your library would be a great addition that is aware of tailwind-expressions.

    Reviewed by johnolos at 2022-03-03 12:22
  • 11. Question: Formatting and Linting

    Hi 👋🏼 First of all thanks for this great project 🙏🏼

    I am in the process of replacing "normal" styled components with Tailwind-Styled-Components in a semi large code base. During this I have hit a few questions I hope you might have some suggestions for 🙂

    1. For styled components we are used to formatting the contents of the template using Prettier, any suggestions for automatic formatting of the tw blocks (Mainly using vs code)

    2. Linting the tailwind classes to make sure only existing classes are used, do you know of any solution for this?

    3. Code hints from Tailwind extension inside the templated code strings.
      As seen on the image, the colors are shown in the main portion, but not in the returns.
      image

    Thought this where the place to use tw`text-danger-700` but that seems to not be correct.
    image

    Hope it is okay to post these questions here, and that someone have some nice suggestions 🙂

    Reviewed by kla-trackunit at 2022-02-21 13:27
  • 12. What's the difference between this and Twin.macro? What are the pros and cons of using each?

    This library looks amazing, and seems like it does exactly what I need - enabling me to use Tailwind with React without turning my JSX into an unreadable mess.

    Since I'm new to Tailwind, I'm still trying to find the best way to use it. Can you help me figure out the difference between this library and Twin.macro? What are the pros and cons of using each?

    Reviewed by lumenwrites at 2022-05-13 14:34
  • 13. Auto format on save

    How would I go about getting formatting on save with this package? Really love the direction, but need to be able to paste in tailwind classes into a styled component and for them to automatically be split to each line when saving.

    Reviewed by olavblj at 2022-05-04 11:00
  • 14. $as prop clears merge inheritance

    $as prop appears to break className merging inheritance

    Simple example

    
    // base tw styled component
    export const Heading = tw.p`
      text-4xl font-bold text-gray-700
    `
    
    // extend the base Heading styled component 
    export const Display = tw(Heading)`
      text-6xl
    `
    
    const WithoutAs = ({children}) => {
        return (
          // without the $as prop, all classnames will be merged in correctly.
          // text-6xl font-bold text-gray-700 border-2 p-4
          <Display className="border-2 p-4">{children}</Display>
        )
    }
    
    const WithAs = ({children}) => {
        return (
         // with the $as prop, only the most recent component's classes will be used
         // text-6xl border-2 p-4
          <Display className="border-2 p-4" $as="h1">{children}</Display>
        )
    }
    
    Reviewed by randallmlough at 2022-04-29 22:24
  • 15. Using arbitrary values

    Hello, it would be nice to have this in your library, or is it already there?

    Example of using arbitrary variants to style elements with a custom selector:

    import tw from 'tailwind-styled-components'
    
    const Button = tw.button`
      bg-black
      [> i]:block
      [> span]:(text-blue-500 w-10)
      [div.container]:(grid m-8)
    `
    
    const Component = () => (
      <Button>
        <i>Icon</i>
        <span>Label</span>
        <div className="container">Container</div>
      </Button>
    )
    
    Reviewed by vladikopl01 at 2022-04-27 18:20
  • 16. Loss of parent component className

    input:

    const Div1 = tw.span`text-red-500`
    const Div2 = tw.div`bg-green-500`
    const Div3 = tw(Div1)`rounded-full`
    const Div4 = tw(Div2)`select-all`
    
    export default () => {
        return <Div3 $as={Div4}>foo</Div3>
    }
    
    

    output:

    <div class="bg-green-500 select-all rounded-full">foo</div>
    

    loss the Div1's className

    Reviewed by YeungKC at 2022-04-18 12:52
CSS Maid 🧹 A tool made for React.js to clean up CSS default styling! Give your CSS a nice reset and style with less hassle!
CSS Maid 🧹 A tool made for React.js to clean up CSS default styling! Give your CSS a nice reset and style with less hassle!

CSS Maid ?? What is it? CSS Maid is a tool for React.js that helps clean up & reset default css! It resets default padding, remove text-decoration on

Sep 1, 2021
Court.css - A naive CSS Utility framework based on JSX and css custom properties

court.css ?? A (work in progress) JSX-based, CSS utility framework with a predic

Mar 14, 2022
Incredible fast template toolkit for making new or re-styling existing components with Tailwind CSS.

Stail Incredible fast template toolkit for making new or re-styling existing components with Tailwind CSS. Why it's needed? First of all, I'm tired fr

Jun 18, 2022
A styled switch for React built using Emotion CSS and Framer motion
A styled switch for React built using Emotion CSS and Framer motion

A styled switch for React built using Emotion CSS and Framer motion

Aug 27, 2021
🏠 Airbnb website using React, Next.js and Tailwind CSS
🏠 Airbnb website using React, Next.js and Tailwind CSS

This example shows how to use Tailwind CSS (v2.2) with Next.js. It follows the steps outlined in the official Tailwind docs.

May 2, 2022
Whirlwind is a utility-first styling framework specifically designed for React Native. It is heavily inspired by Tachyons and Tailwind CSS and uses low-level building blocks for rapidly building custom designs.

React Native Whirlwind ??️ A utility-first CSS framework designed for React Native. Whirlwind is a utility-first CSS framework specifically designed f

May 6, 2022
Starter template for NextJs with TypeScript. Supports Tailwind with CSS-Modules
Starter template for NextJs with TypeScript. Supports Tailwind with CSS-Modules

Starter template for NextJs with TypeScript. Supports Tailwind with CSS-Modules. Jest and @react/testing-library configured and ready to go. Also ESLint, Prettier, Husky, Commit-lint and Atomic Design for components.

Jun 9, 2022
Typograpy components for react and styled-components
Typograpy components for react and styled-components

styled-typography Typograpy components for react and styled-components styled-typography is a small set of components, using styled-components, to bet

May 1, 2022
This repository allows you to create a React template component folder. It optionally includes scss and css files

Generate-React-Components - grc grc let you generate react components in typescript in a folder you specify and it will include .tsx, .scss, .css file

Nov 26, 2021
Framework-agnostic CSS-in-JS with support for server-side rendering, browser prefixing, and minimum CSS generation

Aphrodite Framework-agnostic CSS-in-JS with support for server-side rendering, browser prefixing, and minimum CSS generation. Support for colocating y

Jun 19, 2022
A react component available on npm to easily link to your project on github and is made using React, TypeScript and styled-components.

fork-me-corner is a react component available on npm to easily link to your project on github and is made using React, TypeScript and styled-components.

Feb 27, 2022
Imersão React.js 3º edição. Project using ReactJS, Next JS, and Styled Components for the week challenge by Alura. We created a social network inspired by Orkut.

Example app with styled-components This example features how you use a different styling solution than styled-jsx that also supports universal styles.

Jul 19, 2021
Minimal and performant React component library built on styled-components

Minimal and performant React component library built on styled-components

Jan 3, 2022
Simples Projeto Desenvolvido durante o programa DevInHouse do SENAI-SC, com o intúito de desenvolver um formulário em React utilizando Styled Components
Simples Projeto Desenvolvido durante o programa DevInHouse do SENAI-SC, com o intúito de desenvolver um formulário em React utilizando Styled Components

Simple Styled Form Simples Projeto Desenvolvido durante o programa DevInHouse do SENAI-SC, com o intúito de desenvolver um formulário em React utiliza

Oct 29, 2021
The simplest solution for content loading in React and styled-components.

styled-content-loader The simplest solution for content loading in React and styled-components. Getting Started npm install styled-components styled-c

Jul 13, 2021
Simple Portfolio Using React Hooks & Styled Components
Simple Portfolio Using React Hooks & Styled Components

Said MOUNAIM To view a live example, click here. Getting Started These instructi

Jun 16, 2022
🎥A criação de uma UI para Streaming utilizando React.js, Styled Components junto com Sass.
🎥A criação de uma UI para Streaming utilizando React.js, Styled Components junto com Sass.

Movie Screen - Exercitando React, Styled Components e Sass ??️ Dependencias React Styled Components Sass React Icons ?? Objetivo O principal intuito d

Dec 28, 2021
Styled Components for React Native the way they should have been.

?? Styled-RN Styled Components for React Native the way they should have been. Inspired by this article Intro Why ?? styled-rn it better than ???? sty

Jun 13, 2022
🔧 💅 Jest utilities for Styled Components

Jest Styled Components A set of utilities for testing Styled Components with Jest. This package improves the snapshot testing experience and provides

Jun 21, 2022