1
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 ?

mason
  • 153
  • 2
  • 9

2 Answers2

1

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.

Jello
  • 334
  • 2
  • 10
  • thanks mate, I am new to this, I had tried as you said before but it was a simple mistake ,just to write width: 4rem; instead of width: "4rem", – mason Jan 10 '22 at 06:10
  • No problem! Hope you ahieved it :) – Jello Jan 10 '22 at 07:45
0

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",
   }
}`
Javad
  • 51
  • 1
  • 3
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 10 '22 at 07:29