Skip to content

Latest commit

 

History

History

myStyled

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Pure TypeScript implementation of styled components

Set of components inspired by styled-components

Styles components using stylis under the hood with tagged templates. Includes rule collection for server-side rendering.

Used for a series of tutorial workshops I have put together to demonstrate how Styled Components works under the hood and not intended for production use.


Examples

Functional Component

import myStyled from "packages/myStyled";

const StyledArticle = myStyled("article")`
  @media (min-width: 576px) {
    display: flex;
  }

  header {
    background-color: #aaa;
 
    h1 {
      color: #f00;
    }
  }

  input[type="checkbox"] {
    margin: 0 0.5rem;
  }

  p {
    flex-grow: 1;
  }
`;

export const MyComponent = () => (
  <StyledArticle>
    <header>
      <h1>Hello</h1>
    </header>
    <input type="checkbox" />
    <p>World</p>
  </StyledArticle>
);

Dynamic styling

import myStyled from "packages/myStyled";

type TodoItem = {
  id: string;
  text: string;
  complete: boolean;
};

type TodoProps = {
  todo: TodoItem;
  className?: string;
};

export const Todo = ({ todo: { text }, className }: TodoProps) => (
  <article className={className}>
    {text}
  </article>
);

const MyStyledTodo = myStyled(Todo)`
  background-color: ${({ todo }) => (todo.complete ? "#0f0" : "#f00")}
`;

export const MyComponent = () => (
  <>
    <MyStyledTodo todo={{id: "1", text: "My Todo", complete: true}} />
    <MyStyledTodo todo={{id: "2", text: "My Other Todo", complete: false}} />
  </>
);

Vanilla DOM

import { css } from "packages/myStyled";

const myComponentClassName = css`
  border: 1px solid red;
  
  &:hover {
    border: 1px solid blue;
  }
  
  label {
    border: 1px solid green;
  }
`;

const el = document.createElement("div");
el.classList.add(myComponentClassName);

const label = document.createElement("label");
label.innerText = "My Label";

el.append(label);
document.body.append(el);

Linting CSS-in-JS

An easy way to lint styled components is to re-use the styled-components stylelint configuration. To do this, create a local const called 'styled' and use this variable for the styled components.

For example:

import myStyled from "packages/myStyled";

// 'styled' variable kept separate from the import to get stylelint to 
// perform linting of the embedded CSS
const styled = myStyled;

const Todo$ = styled("article")`
  margin: 2xxx
`;

Result:

Unexpected unknown unit "xxx"