$chiubaca / notes / fleeting / 2021-05-19
  • Read through styled-components docs. Using a lot of JS-in-CSS at work so finally taking the time to understand how this library works…

    • Utalising prop within the styled components requires using string interpolation
      const Button = styled.button`
        /* Adapt the colors based on primary prop */
        background: ${props => props.primary ? "palevioletred" : "white"};
        color: ${props => props.primary ? "white" : "palevioletred"};
    
        font-size: 1em;
        margin: 1em;
        padding: 0.25em 1em;
        border: 2px solid palevioletred;
        border-radius: 3px;
      `;
    
      render(
        <div>
          <Button>Normal</Button>
          <Button primary>Primary</Button>
        </div>
      );e"};
        color: ${props => props.primary ? "white" : "palevioletred"};
    • styled components opens up polymorphic css! extend an existing styled component with styled()
    const TomatoButton = styled(Button)`
      color: tomato;
      border-color: tomato;
    `;
    • nice reference to map how regular css looks vs styled components

    • Define Styled Components outside of the render method!!!

    • & has super powers in styled-components

    • Decoupling your animations keyframes seems nice

    // Create the keyframes
    const rotate = keyframes`
      from {
        transform: rotate(0deg);
      }
    
      to {
        transform: rotate(360deg);
      }
    `;
    
    // Here we create a component that will rotate everything we pass in over two seconds
    const Rotate = styled.div`
      display: inline-block;
      animation: ${rotate} 2s linear infinite;
      padding: 2rem 1rem;
      font-size: 1.2rem;
    `;
    
    render(<Rotate>&lt; 💅🏾 &gt;</Rotate>);
    • Write global styles with <ThemeProvider> and createGlobalStyle

    • You can overide styling from another component states!

    • you can write inline css-(ish) as sort of way to bypass styled components entirely

    • It’s still possible to target children classNames within a styled component

    const Thing = styled.div`
      color: blue;
    
      .something {
        border: 1px solid; // an element labeled ".something" inside <Thing>
        display: block;
      }
    `;
    
    render(
      <Thing>
        <label htmlFor="foo-button" className="something">
          Mystery button
        </label>
        <button id="foo-button">What do I do?</button>
      </Thing>
    );
Edit on GitHub ✏️

Hey I'm Alex Chiu 👋. These are my notes for literally anything.

I'm using the Zettelkasten method to organise my thoughts here.

My more polished writings are published to my main blog at chiubaca.com

Follow me on: Github / X (Twitter) / Mastodon / LinkedIn