Home > Software design >  Add background color conditionally in styled components
Add background color conditionally in styled components

Time:06-08

Hello i have the below code. I want to make a styled component which takes the backgroundColor as a prop. The below code doesnt work.

import { colors } from "styling/variables";
import styled from "@emotion/styled";

const Badge = styled("span")(
  {
    padding: 5,
    borderRadius: 10,
    // backgroundColor: colors.red,
    color: colors.white,
    fontSize: "0.7rem",
    marginRight: 10,
    width: "60px"
  },
  props => ({
    backgroundColor: props.color
  })
);

function Priority() {
  return <Badge color={colors.balck}>High</Badge>;
}

export default Priority;

CodePudding user response:

You need to pass props to the Priority styled component

function Priority(props) {
  return <Badge color={colors.black}>High</Badge>;
}

Then add the props to the styled :

const Badge = styled.span`
    padding: 5,
    borderRadius: 10,
    // backgroundColor: colors.red,
    color: colors.white,
    fontSize: "0.7rem",
    marginRight: 10,
    width: "60px"
    backgroundColor: ${p => p.color}
`;

CodePudding user response:

I have written the below code, where you can see I have set the background color with props.

import styled from "@emotion/styled";
const variantsBg = {
  primary: #fff,
};

const Badge = styled.span`
  background: ${props => variantsBg[props.variant]};
`;

export default Badge;

//How you can pass the props in Badge component

<Badge variant="primary" />
  • Related