Arshia Arsh1a Faraji
Arshia Arsh1a Faraji

Reputation: 107

How to pass props to styled component when using theme?

I want to use the color prop I get from Button component to use it for background color using styled component theme.

import React from "react";
import styled from "styled-components";

const StyledButton = styled("button")<{
  color: string;
  padding: string;
}>`
  background: ${(props) => props.theme.colors.primary};
  outline: none;
  box-shadow: none;
  border: none;
  padding: ${(props) => props.padding};
  border-radius: 5px;
  color: white;
  font-size: ${(props) => props.theme.fontSizes.small};
  margin: 0 10px;
`;

interface Props extends React.ComponentPropsWithoutRef<"button"> {
  color?: string;
  padding?: string;
}

const Button = ({ children, color, padding }: Props) => {
  return (
    <StyledButton color={color!} padding={padding!}>
      {children}
    </StyledButton>
  );
};
export default Button;

Theme:

import { DefaultTheme } from "styled-components";

const theme: DefaultTheme = {
  colors: {
    primary: "#5A8DEE",
    boldPrimary: "#274d8c",
    lightPrimary: "#dae3f5",
    green: "#5CCf4C",
    gray: "#F2F4F4",
    white: "#FFFFFF",
    text: "#5f5f63",
    lightText: "#878791",
  },
  fontSizes: {
    extraSmall: "0.75rem",
    small: "1rem",
    medium: "1.25rem",
    large: "1.50rem",
  },
};

export default theme;

Like when I get primary from Button props, I want it to get the color codes from the theme context I made.

Upvotes: 3

Views: 7920

Answers (1)

Drew Reese
Drew Reese

Reputation: 203512

If I'm understanding your question correctly you've several theme colors and you want to specify which to use from a prop passed to a component.

Given the theme colors:

colors: {
  primary: "#5A8DEE",
  boldPrimary: "#274d8c",
  lightPrimary: "#dae3f5",
  green: "#5CCf4C",
  gray: "#F2F4F4",
  white: "#FFFFFF",
  text: "#5f5f63",
  lightText: "#878791",
}

You can specify a color prop:

interface Props extends React.ComponentPropsWithoutRef<"button"> {
  color?: string;
  padding?: string;
}

In the styled component use the passed color prop to access into your theme

const StyledButton = styled("button")<{
  color: string;
  padding: string;
}>`
  background: ${(props) => props.theme.colors[props.color]}; // <-- access by dynamic key
  outline: none;
  box-shadow: none;
  border: none;
  padding: ${(props) => props.padding};
  border-radius: 5px;
  color: white;
  font-size: ${(props) => props.theme.fontSizes.small};
  margin: 0 10px;
`;

const Button = ({ children, color, padding }: Props) => {
  return (
    <StyledButton color={color} padding={padding!}>
      {children}
    </StyledButton>
  );
};

Then specify the color you want to use:

<Button color="primary" />
<Button color="boldPrimary" />
...etc...

Upvotes: 4

Related Questions