Search code examples
cssreactjspropertiesstyled-componentsemotion

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


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 ?


Solution

  • 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.