Using state variable in styled components

Viewed 442

Im trying to make a button that changes state depending on the value of a property on an object.

here is the styled component

  const Btn = styled.button`
  border-radius: ${props => props.theme.radius};
  padding:5px 10px;
  background-color:${ sub.saved ? 'green' : 'red'}
  &:hover{
    cursor:pointer;
  }
`

and here is the component that it is being used inside of

const DisplaySubs = ({ queryResults, setSavedFunction, saved }) => {
  return (
    <>
      <Total>{queryResults.length} results found </Total>
      <UL>
        {queryResults.map((sub, index) => {
          return (
            <LI onClick={() => {
              window.open(`https://www.reddit.com/${sub.title}`)
            }

            }>
              <H4>{sub.title}</H4>
              <P>{sub.description}</P>
              <Btn onClick={(e) => {
                e.stopPropagation()
                sub.saved = !sub.saved

              }}>Save</Btn>
            </LI>
          )
        })}
      </UL >
    </>
  )
}
2 Answers

Instead of creating a component like this, you can write a simple functional component like

const Btn = ( props ) => {
 <div style={{
      borderRadius: {props.theme.radius},
      padding:"5px 10px",
      backgroundColor: {props.sub.saved ? 'green' : 'red'}
 }}>
   {props.children}
 </div>
}

You can call this in your Main Container by <Btn props={props}>Button<Btn>

For a javascript project:

// you "add" the interface to button, so you can access this custom properties
export const Btn = styled.button`
  padding: 5px 10px;

  background-color: ${(props) => (props.isSaved ? "green" : "red")};

  &:hover {
    cursor: pointer;
  }
`;

For a typescript project, you can use interface to set custom properties, like:

// Create an interface defining custom properties to button
interface BtnProps {
  isSaved: boolean;
}

// you "add" the interface to button, so you can access this custom properties
export const Btn = styled.button<BtnProps>`
  padding: 5px 10px;

  background-color: ${(props) => (props.isSaved ? "green" : "red")};

  &:hover {
    cursor: pointer;
  }
`;

and your button:

// set isSaved property to button component, 
// so you will have access to it on styled-components.
<Btn isSaved={sub.saved}
onClick={(e) => {
                e.stopPropagation()
                sub.saved = !sub.saved

}}>Save</Btn>
Related