A utility-first CSS-in-JS framework built for React. 💅👩‍🎤⚡️

  • By Greg Bergé
  • Last update: Dec 27, 2022
  • Comments: 17

xstyled

A utility-first CSS-in-JS framework built for React.

License npm package npm downloads CircleCI codecov Code style

npm install @xstyled/styled-components styled-components

Docs

See the documentation at xstyled.dev for more information about using xstyled!

Quicklinks to some of the most-visited pages:

Example

import { x } from '@xstyled/styled-components'

function Example() {
  return (
    <x.div p={{ _: 3, md: 6 }} bg="white" display="flex" spaceX={4}>
      <x.div flexShrink={0}>
        <x.img h={12} w={12} src="/img/logo.svg" alt="xstyled Logo" />
      </x.div>
      <x.div>
        <x.h4
          fontSize={{ _: 'md', lg: 'xl' }}
          fontWeight="medium"
          color="black"
        >
          xstyled
        </x.h4>
        <x.p color="gray-500">A CSS-in-JS framework built for React.</x.p>
      </x.div>
    </x.div>
  )
}

License

Licensed under the MIT License, Copyright © 2019-present Greg Bergé.

See LICENSE for more information.

Github

https://github.com/gregberge/xstyled

Comments(17)

  • 1

    Babel Macros - not working

    Hi, it would seem I cannot import the macro version of styled-components:

    https://www.styled-components.com/docs/tooling#babel-macro

    import styled from '@xstyled/styled-components/macro';
    

    Failed to compile. Error: Cannot find module '@xstyled/styled-components/macro'

    Thought trying also importing from @xstyled/macro but no luck.


    Importing directly from styled-components does work well:

    import styled from 'styled-components/macro';
    

    Background:

    We have an app based on create-react-app, not ejected, and not using rewire, because CRA supports babel macros, and I wish to utilize that ability to be able to use the babel-plugin-styled-components plugin.

    I need this so my styled-components will be generated with a real display name, to be able to access components in enzyme unit tests.

    Related thread

  • 2

    New built-in utility: textSize

    🚀 Feature Proposal

    I propose a new builtin textSize utility, that combines font size and line height.

    Motivation

    I love the inspirations xstyled 2 took from Tailwind, especially the new utility style props. One thing that I'm missing is Tailwind's combination of font size and line height, which makes an awful lot of sense. Unless you have very specific design needs, these two properties are always coupled.

    Example

    <x.div textSize="xl">...</x.div> = <x.div fontSize="xl" lineHeight="xl">...</x.div>

    Pitch

    xstyled 2 already has a lot of builtin utilities and a default theme, which is great! I think taking more inspiration from Tailwind can carve out a niche for xstyled among the dozens of low-level CSS-in-JS libraries by providing a more complete utility-based styling solution.

  • 3

    Any future plans on adding types?

    Hey! I've been a long-time user of styled-components and thought I'd give xstyled a try since I could totally relate and understand the motivation behind it!

    But regarding the topic of this issue, would it be possible to import styled-components/styled-system's preexisting type library? And if not, are there future plans to add types?

    Anyways, I really appreciate your work on this library!

  • 4

    Compatibility with react native

    Would be possible to use this project with react-native?. I tried, but I get this error:

    scStyled__default.div is not a function

    I could see under Box.js it's using a div. (https://github.com/smooth-code/xstyled/blob/master/packages/styled-components/src/Box.js#L4)

    Makes sense to create another package to support react-native projects? what do you think? I can try to help

  • 5

    styled.box is different from styled.div`${system}`

    🐛 Bug Report

    I think these should behave the same way, but they don't:

    const Inner = styled.box``
    const Outer = styled(Inner)`color: red;`
    
    // Unexpectedly GREEN
    <Outer color="green">This should be RED</Outer>
    
    const Inner = styled.div`${system};`
    const Outer = styled(Inner)`color: red;`
    
    // Works as expected
    <Outer color="green">This is RED</Outer>
    

    To Reproduce

    https://codesandbox.io/s/funny-brook-cy9ne?file=/src/App.js

    Versions

    This behaves the same way on 1.x and 2.x so it's not a regression, it's just unexpected

  • 6

    override shouldForwardProp

    Summary

    Currently, some props are being passed and written to the DOM. Emotion is handling this by using is-prop-valid which checks if the prop is a valid html attribute before writing. Here

    Test plan

    image

  • 7

    fix(breakpoints): races in useViewportWidth

    Summary

    The main fix here is changing the initial state from null to window.innerWidth, so that there isn't a useless transition from (for example) useDown('md') = true to useDown('md') = false when the application loads. Depending on the application, the rerendering penalty can be heavy.

    While we're here, notice that we can make a couple related changes: First, since the initial state is set properly, we don't need a layout effect, instead we can use a normal effect. Second, swap the order of listener and setWidth to avoid the tiny race between them.

    Test plan

    This cropped up for me in storybook. I have a component that measures its container to make image layout decisions. On the first load of the app, it would work, but on hot reload, the image would be the wrong size.

    The problem is that useDown('md') returns the wrong value the first time. It was okay on initial app load because image loading slowed things down enough that useDown('md') would return the right value before the measurement. However on hot reload, when the image is already loaded, the measurement would fire in the window of time between the bogus useDown and the right useDown.

    Note that the measurement code also reruns on resize, but since there's no resize occurring, it wouldn't know to remeasure.

    Making this change fixed the problem for me.

  • 8

    Add transient Props to @xstyled/emotion

    Summary

    Emotion allows its consumer apps to change styles based on props. See here. By default, emotion would prevent invalid props from being rendered to the DOM element but since xstyled is overriding the "shouldForwardProp" this functionally is being removed.

    Styled-components handle this by prefixing the prop name with a dollar sign $. Transient Props

    Do you see any downside or conflict by doing something this? @agriffis @gregberge

    Test plan

    image

    My previous PR was causing some issues with the "as" so this is why I just remove the ones with the $.

  • 9

    xstyled took a sharp turn into the abomination domain

    as a 2-years "veteran" avid user of xstyled, I saw the new website (and new approach) and was SHOCKED.

    as someone which writes CSS for about 20 years, I believe it is a complete abomination to write styles as props on the component themselves and not keep pure separation of concerns between components (or HTML elements) and their styles.

    I use styled components in a very complex manner and this new approach is far too basic and promotes dirty coding where developers add a mountain of props, all mixed together, some CSS-related and some logic-related, not to mention it's impossible to properly use & read CSS variables (custom properties) this way.

    Your choice where to take xstyled has saddened me greatly and I want to express me feelings so you would know that there is at least one user which is believes this is a mistake.

    Also, the docs are horrible. Cannot find any real information on th utility, or real examples of how it can be used (since I never remember)

    nor can I find any information regarding extending a an already styled component. The "search" bar of the new website really gives poor results.

  • 10

    th utility returns a function and not a value

    (version 1.19.1)

    Hi, I'm trying to create automatic CSS variables out of JSX, with a defined theme file:

    import React from 'react'
    import styled, { getColor } from '@xstyled/styled-components'
    import { getCSSVars } from 'utils' // <-- receives props and convert to CSS variables
    
    const COLORS = {
      blue: getColor('blue') // <- returns a function and not a value
    }
    
    const StyledTag = styled(StyledTagBase)`
      ${getCSSVars('color')}
    `
    
    // using icons from:
    // https://svgbox.net/
    const Tag = ({ children, color = COLORS.blue }) => (
    	<StyledTag color={COLORS[color]} onClick={onClick}>
          {children}
        </StyledTag>
    )
     
    export default Tag
    

    I have a problem that using th or getColor shorthand, returns a function, rather than a value:

    blue: getColor('blue')
    

    What should be done? Can a value be forced out of it?

    Thanks for your kind help!

  • 11

    Generated class names aren't legible

    🐛 Bug Report

    Component class names are not using display names. They look like this:

    <div class="sc-bdVaJa cyWyZX">
      Something
    </div>
    

    To Reproduce

    Here are my dependencies:

    • @xstyled/styled-components 1.16.0
    • @xstyled/system 1.16.0
    • styled-components 4.4.1
    • babel-plugin-styled-components 1.10.7

    Expected behavior

    Previously without xstyled, I would get this class name in my styled components:

    <div class="ComponentDisplayName_Text-sc-bdVaJa cyWyZX">
      Something
    </div>
    
  • 12

    Why height and width are shortened?

    I usually do not use shortened props in order to improve readability, and upon looking here and here I wonder why height and width only exists in shortened version.

  • 13

    Incorrect breakpoint with useBreakpoint hook

    🐛 Bug Report

    According to the documentation, md breakpoint should be returned at @media (min-width: 768px) { ... }. Instead it triggers at @media (min-width: 769px) { ... }

    To Reproduce

    • Go to codesandbox link
    • Using dev tools, change device width to 768
    • Breakpoint shown on screen will be 'sm'

    Expected behavior

    • Breakpoint shown on screen should be 'md'

    Link to repl or repo (highly encouraged)

    https://codesandbox.io/s/confident-tdd-mhwndm?file=/src/App.js

    ## Binaries:
     - Node: 16.16.0 - ~/.nvm/versions/node/v16.16.0/bin/node
     - Yarn: 1.22.19 - ~/.nvm/versions/node/v16.16.0/bin/yarn
     - npm: 8.11.0 - ~/.nvm/versions/node/v16.16.0/bin/npm
    ## npmPackages:
     - @xstyled/styled-components: ^3.6.0 => 3.7.0 
     - styled-components: ^5.3.5 => 5.3.6 
    
  • 14

    xstyled v 3.7.0 typescript error

    🐛 Bug Report

    After updating @xstyled/styled-components and @xstyled/system both to v "3.7.0", following TS issue appeared on all places, where ${system} is used. In version 3.6.0 everything was fine.

    To Reproduce

    Update to v 3.7.0, as described above and check TS (in. CLI or in IDE)

    Expected behavior

    No errors.

    Actual result

    Snímek obrazovky 2022-10-28 v 9 33 24 Snímek obrazovky 2022-10-28 v 9 31 48

    Full dependency list

    "dependencies": {
        "@apollo/client": "3.7.1",
        "@lingui/react": "3.14.0",
        "@reduxjs/toolkit": "1.8.6",
        "@sentry/react": "7.17.1",
        "@sentry/tracing": "7.17.1",
        "@xstyled/styled-components": "3.7.0",
        "@xstyled/system": "3.7.0",
        "babel-plugin-macros": "3.1.0",
        "dayjs": "1.11.6",
        "debug": "4.3.4",
        "dotenv-safe": "8.2.0",
        "graphql": "16.6.0",
        "history": "5.3.0",
        "make-plural": "7.1.0",
        "ramda": "0.28.0",
        "react": "18.2.0",
        "react-day-picker": "7.4.10",
        "react-dom": "18.2.0",
        "react-helmet": "6.1.0",
        "react-hook-form": "7.38.0",
        "react-image": "4.0.3",
        "react-redux": "8.0.4",
        "react-router": "6.4.2",
        "react-router-dom": "6.4.2",
        "react-select": "5.5.7",
        "redux-first-history": "5.1.1",
        "redux-saga": "1.2.1",
        "serialize-javascript": "6.0.0",
        "serve": "14.0.1",
        "styled-components": "5.3.6",
        "vite-aliases": "0.8.6"
      },
      "devDependencies": {
        "@babel/core": "7.19.6",
        "@babel/preset-typescript": "7.18.6",
        "@faker-js/faker": "7.6.0",
        "@graphql-codegen/cli": "2.13.8",
        "@graphql-codegen/typescript": "2.8.0",
        "@graphql-codegen/typescript-operations": "2.5.5",
        "@lingui/cli": "3.14.0",
        "@lingui/core": "3.14.0",
        "@lingui/macro": "3.14.0",
        "@ls-lint/ls-lint": "1.11.2",
        "@storybook/addon-actions": "6.5.13",
        "@storybook/addon-essentials": "6.5.13",
        "@storybook/addon-interactions": "6.5.13",
        "@storybook/addon-links": "6.5.13",
        "@storybook/builder-vite": "0.2.5",
        "@storybook/react": "6.5.13",
        "@storybook/testing-library": "0.0.13",
        "@types/debug": "4.1.7",
        "@types/jest": "29.2.0",
        "@types/ramda": "0.28.18",
        "@types/react": "18.0.24",
        "@types/react-dom": "18.0.8",
        "@types/react-helmet": "6.1.5",
        "@types/serialize-javascript": "5.0.2",
        "@types/styled-components": "5.1.26",
        "@types/xstyled__system": "1.19.3",
        "@typescript-eslint/eslint-plugin": "5.41.0",
        "@typescript-eslint/parser": "5.41.0",
        "@vitejs/plugin-react": "2.2.0",
        "babel-loader": "8.2.5",
        "concurrently": "7.5.0",
        "eslint": "8.26.0",
        "eslint-config-airbnb-base": "15.0.0",
        "eslint-config-prettier": "8.5.0",
        "eslint-plugin-import": "2.26.0",
        "eslint-plugin-local-rules": "1.3.2",
        "eslint-plugin-prettier": "4.2.1",
        "eslint-plugin-react": "7.31.10",
        "eslint-plugin-react-hooks": "4.6.0",
        "eslint-plugin-react-perf": "3.3.1",
        "jest": "29.2.2",
        "plop": "3.1.1",
        "rollup-plugin-visualizer": "5.8.3",
        "ts-jest": "29.0.3",
        "typescript": "4.8.4",
        "vite": "3.2.0"
      }
    
  • 15

    feat: support react-native

    Summary

    Hello guys! basically I'm trying to finalize a PR that was adding support for react-native. Can find out a little more about it here: https://github.com/gregberge/xstyled/pull/273, thanks @diegotsi

    My idea is basically the same as this PR except that I'll be adding the default use without utility props and the x function with utility props.

    Test plan

    const WithoutUtilityProps = styled.View`
      background-color: cool-gray-500;
      padding: 2;
    `;
    
    const WithConfig = styled.View.withConfig({})`
      background-color: rose-900;
      padding: 2;
    `;
    
    const StyledSomeComponent = styled(View)`
      background-color: teal-900;
      padding: 2;
    `;
    
    const WithUtilityProps = styled.ViewBox``;
    
    const UsingAS = styled.View``;
    
    const Test = () => {
      return (
        <ThemeProvider theme={defaultTheme}>
          <x.View p={2} bg="blue-gray-900">
            <x.Text color="blue-gray-500">Text X elements</x.Text>
          </x.View>
          <UsingAS as={x.Text} p={2} bg="emerald-500">
            Now is a x.Text with all props from Text (RN) + utility props from
            xstyled
          </UsingAS>
          <WithUtilityProps p={2}>
            <x.Text>With Utility Props</x.Text>
          </WithUtilityProps>
          <WithConfig>
            <x.Text color="white">With Config</x.Text>
          </WithConfig>
          {/*@ts-expect-error */}
          <WithoutUtilityProps bg="black">
            <x.Text>Without Utility Props</x.Text>
          </WithoutUtilityProps>
          <StyledSomeComponent>
            <x.Text color="white">Styled(SomeComponent)</x.Text>
          </StyledSomeComponent>
        </ThemeProvider>
      );
    };
    

    Working with the latest react-native template:

    Captura de Tela 2022-08-21 às 08 32 37

    types

    working

  • 16

    useUp & useDown accept number values but don't support them

    🐛 Bug Report

    Hooks useUp & useDown have following type declaration:

    declare const useUp: (key: string | number) => boolean;
    declare const useDown: (key: string | number) => boolean;
    

    but calling useUp(1024) always returns false.

    To Reproduce

    const App = () => {
      const upLg = useUp(1024);
    
      return <>{upLg ? ">lg" : "<lg"}</>
    }
    
    

    Expected behavior

    useUp & useDown should either disallow number values or handle them properly.

  • 17

    Remove redundant styling props in the next major version of xstyled

    There are a number of redundant props: bg vs backgroundColor, maxW vs maxWidth, maxH vs maxHeight

    On the surface this doesn't seem like a big deal, but if you're making a component library using xstyled which has some base styling and allows overrides by the consumer, this could lead to issues if they don't match using the exact same prop.

    We should choose to favor either the verbose or short versions and deprecate+remove the others to reduce complexity.