Spreading Props TypeScript with React and Styled Components

Viewed 2022

I seem to be having troubles spreading the props in a component that uses StyledComponents under the hood. Whenever I try to pass a prop not defined in the interface (a style tag, for instance), I get an error. Here´s my current implementation:

interface IParagraphProps {
  text: string;
}

const StyledParagraph = styled.p`
  max-width: 90%;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
`;



const Paragraph = (props: IParagraphProps) => {
  const { text, ...rest } = props;
  return  (
    <StyledParagraph {...rest}>{text}</StyledParagraph>
  ) 
};
export default Paragraph;

EDIT: Here´s the error: Property 'style' does not exist on type 'IntrinsicAttributes & IParagraphProps'. And the place where I use this component:

const Card = () => {
  return (
        <Paragraph
            style={{ marginTop: "1rem" }}
          text="whatever"
        />)

};

2 Answers

You're giving a style property to your Paragraph component, however this component only expect a text property. You should either remove that property:

const Card = () => {
  return (
        <Paragraph
          text="whatever"
        />)
};

or you should add the property to your component:

interface IParagraphProps {
  text: string;
  style: React.CSSProperties;
}

If you want to match whole the possible props you can do something like that:

type IParagraphProps =  {
  text: string;
} & React.ComponentProps<typeof StyledParagraph>

This is similar to the first answer but using an interface instead of a type:

If you want to match whole the possible props you can do something like that:

type IParagraphProps = { text: string; } & React.ComponentProps

If you want to be able to spread any props other than text to the StyledParagraph, you need to specify in the IParagraphProps interface that it can accept any of the props for the StyledParagraph.

interface IParagraphProps extends React.ComponentPropsWithoutRef<typeof StyledParagraph> {
  text: string
}

^^^ Now the props for this component are specified as text: string + every prop that StyledParagraph accepts. If you want to allow a ref as well you can change ComponentPropsWithoutRef to ComponentPropsWithRef and use React.forwardRef.

Source: https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/basic_type_example/#useful-react-prop-type-examples

Related