Search code examples
typescriptstyled-components

Styled Components hiding HTML attributes in Typescript


I create a standard Styled Component like:

export type ContainerProps = {
  color: string;
};

export const Container = styled.div<ContainerProps>`
  color: ${p => p.color};
  background: blue;
  width: 100%
`;

When I want to use this component in JSX I have all the HTML attributes available as props.

Is there any way how to restrict these, so that the user can use only props specified in props type?


Solution

  • I doubt you will be able to achieve it, check the implementation here

    A naive approach can be, to create another component and export this.

    export const StyledContainer = styled.div<ContainerProps>`
      color: ${(p) => p.color};
      background: blue;
      width: 100%
    `;
    
    export const Container: FC<ContainerProps> = (...props) => (
      <StyledContainer {...props} />
    );
    

    SC adds extra default HTML props(onClick, onBlur etc), If we provide FC it'll only accept Type props.

    export type ContainerProps = {
      color: string,
    };
    export const Container: FC<ContainerProps> = styled.div<ContainerProps>`
      color: ${(p) => p.color};
      background: blue;
      width: 100%
    `;