I want to reuse certain CSS properties in Emotion/styled component

Viewed 1110
import styled from '@emotion/styled';

type ColorProps = {
    Coloured: boolean,
}

const BoxStyled = styled.div`
    ${(props:ColorProps) => 
    props.Coloured ? {
    
    background: "#304f8f",
    border: "1.85px solid #304f8f",
    color: "white",
    width: "4rem",
    height: "2.5rem",
    padding:"0 11px" 
} :
{
    
    border: "1.98px solid #2c8090",
    width: "4rem",
    height: "2.5rem",
    padding:"0 11px" 
}
}`

here in BoxStyled I don't want to write width: "4rem", height: "2.5rem", padding:"0 11px" twice how do I achieve this ?

2 Answers

Use css to make a variable of style.

import { css } from 'styled-components'

const reuse = css`
  width: 4rem;
  height: 2.5rem;
  padding: 0 11px;
`

const StyleA = styled.div`
  background-color: black;
  ${reuse}
`

const StyleB = styled.div`
  background-color: red;
  ${reuse}
`

Check this for more information.

You can define the main style and when needed to change overwrite new style.

import styled from '@emotion/styled';

type ColorProps = {
    Coloured: boolean,
}

const BoxStyled = styled.div`

    border: "1.98px solid #2c8090",
    width: "4rem",
    height: "2.5rem", 
    padding:"0 11px" 

    ${(props:ColorProps) => 
    props.Coloured && {
      background: "#304f8f",
      border: "1.85px solid #304f8f",
      color: "white",
   }
}`
Related