Home > Mobile >  Reducing Repetitive Code Within Styled-components
Reducing Repetitive Code Within Styled-components

Time:02-23

I'm using styled-components in a react project, and wondering if there's a way to reduce these 3 blocks that are repeating, with the only difference being the color of the border.

Initially, I'm thinking of creating an object that maps out the possible alert values (success, warning, danger), and add appropriate color as their keys, however I'm not sure where it to put that object.


const customStyles = {

  ${({ alert }) =>
    alert === "success" &&
    css`
      border: 1px solid green;
  `}

  ${({ alert }) =>
    alert === "warning" &&
    css`
      border: 1px solid orange;
  `}

  ${({ alert }) =>
    alert === "danger" &&
    css`
      border: 1px solid red;
  `}

}

const Input = styled.input`
  ${customStyles}
`;

CodePudding user response:

How about a function you can reuse that returns the right color based on the value?

Something like this:

function getAlertColor(alert){
  switch (alert) {
    case "success":
      return "green"
    case "warning":
      return "orange"
    case "danger":
      return "red"
  }
}

const Input = styled.input`
  border: ${props => `1px solid ${getAlertColor(props.alert)};`};
`;
  • Related