0
votes

I am trying to create a styled-components button with a primary CTA version.

<Button primary type='submit' disabled={!(formik.dirty && formik.isValid) || formik.isSubmitting}>Submit</Button>
<Button>Cancel</Button>

I can access the theme in the code below, just not from within the props.primary conditional. When I console.log props, the theme is there. The font-weight works, and it works fine if I substitute a hex value for the primary color and background-color. Any ideas?

export const Button = styled.button`
  appearance: none;
  -webkit-appearance: none;

  color: ${(props) => props.theme.btnText};
  background-color: ${(props) => props.theme.btnBg};

  font-size: 1.8rem;
  font-weight: 500;

  margin-right: 1rem;
  margin-top: 2rem;
  margin-bottom: 2rem;
  padding: 1.3rem 3.4rem;

  border-radius: 4px;
  border: 1px solid ${(props) => props.theme.btnBorder};
  outline: none;
  cursor: pointer;

  display: inline-block;
  text-align: center;
  text-decoration: none;
  white-space: nowrap;

  ${(props) => {
    if (props.primary) {
      return `
        font-weight: 700;
        color: ${(props) => props.theme.btnPrimText};
        background-color: ${(props) => props.theme.btnPrimBg};
      `
    }
    return null
  }}
`
1

1 Answers

0
votes

That behavior its because you are "getting" props twice:

/// PROPS GET
${(props) => {
    if (props.primary) {
      return `
        font-weight: 700;
                 // YOU ALREADY GET PROPS ABOVE
        color: ${(props) => props.theme.btnPrimText};
                 // YOU ALREADY GET PROPS ABOVE
        background-color: ${(props) => props.theme.btnPrimBg};
      `
    }
    return null
  }}

Your code should be like this:

${(props) => {
    if (props.primary) {
      return `
        font-weight: 700;
        color: ${props.theme.btnPrimText};
        background-color: ${props.theme.btnPrimBg};
      `;
    }
    return null;
  }}

And a better way to do this would be:

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

${(props) =>
    props.primary &&
    css`
      font-weight: 700;
      color: ${props.theme.btnPrimText};
      background-color: ${props.theme.btnPrimBg};
    `}