Search code examples
cssreactjsantdstyled-components

Change color of Title Component in Ant Design using Styled Component?


I am using Ant Design alongside styled components for my application.

I have a NavBar which component which uses a H1 Component.

H1.tsx

import React from 'react';
import { Typography } from 'antd';
import styled from 'styled-components';

const { Title } = Typography;

const TypographyWrapper = styled.div`
  font-family: 'Muli', sans-serif;
`;

interface H1Props {
  children?: String;
}

export const H1: React.SFC<H1Props> = ({ children, ...rest }) => {
  return (
    <TypographyWrapper>
      <Title style={{ margin: '0px' }} {...rest}>
        {children}
      </Title>
    </TypographyWrapper>
  );
};

export default H1;

Navbar.tsx

import React from 'react';
import { primary, monochrome } from '../colors/Colors';
import styled from 'styled-components';
import { NavbarConstants } from '../../config/stringConstants';
import H1 from '../typography/H1';

const Wrapper = styled.div`
  background-color: ${primary['Blue-400']}
  width: 100%;
  display: flex;
  flex-direction: row;
  padding: 30px;
  align-items: center;
`;

const StyledH1 = styled(H1)`
  color: ${monochrome.offWhite};
`;

interface NavbarProps {}

export const Navbar: React.SFC<NavbarProps> = () => {
  return (
    <Wrapper>
      <StyledH1>{NavbarConstants.NAVBAR_TITLE}</StyledH1>
    </Wrapper>
  );
};

I am looking to change the color of the H1 text i.e. color: ${monochrome.offWhite} but I cannot seem to target the component at all.

From the console, it is override by h1.ant-typography, .ant-typography h1. I tried variations of selectors to target this, but to no avail.

How can I modify the text color using styled components?


Solution

  • Your styles are getting overridden with Antd styles, you can add a style with more specificity to override them.

    const StyledH1 = styled(H1)`
      &.ant-typography {
        color: ${monochrome.offWhite};
      }
    `;