Skip to content

Latest commit

 

History

History
34 lines (27 loc) · 788 Bytes

conditional-css-in-styled-components.md

File metadata and controls

34 lines (27 loc) · 788 Bytes

Conditional CSS In Styled Components

Category: React

Styled components support dynamic styling with conditional CSS. This example will create a styled h1 in TypeScript with an optional parameter that can be used to specify display of a border.

import styled, { css } from 'styled-components';

export const Heading = styled.div<{border?: boolean}>`
  font-size: 32px; 
  margin: 20px;
  text-align: center;
  padding: 20px;
  ${props => props.border === true && css`
      border: 1px solid #0f0f0f;
  `}
`;

Use the styled component as follows:

const Banner = () => {
  return(
    <>
      <Heading border={true}>Styled h1 with a border</Heading>
      <Heading>Styled h1 without a border</Heading>
    </>
  );
}

export default Banner;