Skip to content

Instantly share code, notes, and snippets.

@gusalbukrk
Last active January 27, 2021 23:37
Show Gist options
  • Save gusalbukrk/68077f7d7bbf07cab371d163efb28637 to your computer and use it in GitHub Desktop.
Save gusalbukrk/68077f7d7bbf07cab371d163efb28637 to your computer and use it in GitHub Desktop.
#styled-components #styled #components

Basics

basic

import styled from 'styled-components';

const Header = styled.h1`
  color: red;
`;

function App() {
  return <Header>My header</Header>;
}

extending a styled component

const Header = styled.h1`
  color: red;
  background-color: pink;
`;

const Header2 = styled(Header)`
  text-decoration: underline;
`;

extending a non-styled component

  • the styled method works perfectly on all of your own or any third-party component
  • as long as they attach the passed className prop to a DOM element
function HeaderBase({ className }) {
  return <h1 className={className}>Header</h1>;
}

const Header = styled(HeaderBase)`
  color: red;
`;

adapting based on props

const Header = styled.h1`
  text-transform: ${(props) => (props.uppercase ? 'uppercase' : 'lowercase')};
`;

adpating based on props, multiline

import styled, { css } from 'styled-components';

// `css` must be imported from styled-components
const Header = styled.h1`
  color: purple;
  ${(props) =>
    props.special &&
    css`
      background-color: pink;
      text-decoration: underline;
    `}
`;

nested styles

const Header = styled.h1`
  color: blue;

  &.special {
    background-color: lightblue;
  }
`;

media query

const Header = styled.h1`
  color: red;

  @media (max-width: 600px) {
    color: purple;
  }
`;

Theme

  1. make a theme file and export a default theme object
  2. import theme and ThemeProvider
  3. wrap component with the ThemeProvider
  4. access theme properties inside a wrapped component or one of its children
// Theme.js
const theme = {
  myColor: "purple",
};

export default theme;

// App.js
import styled, { ThemeProvider } from "styled-components";
import theme from "./Theme";

const Header = styled.h1`
  color: ${props => props.theme.myColor};
`;

function App() {
  return (
    <ThemeProvider theme={theme}>
      <Header>Title</Header>
    </ThemeProvider>
  );
}

export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment