SethBarton
SethBarton

Reputation: 133

Additional Arguments to Styled Components in React with Typescript

I have a styled component I need to reuse. It looks like this:

export const FormFooter = styled.div(
  ({ theme }) => `
  padding: ${theme.spacing(3)}px;
  border-top: 1px solid ${theme.palette.lighterGray};
  position: sticky;
  width: 100%;
`,
)

This component is used elsewhere in our codebase and but there's one application where I need it to behave slightly differently. Specifically, I need position to be absolute and bottom to be '0'.

I want to be able to pass additional arguments to this component and set default values for them. Is there a way to do that?

I'm looking for something like:

export const FormFooter = styled.div<{position?: string, bottom?: string}>(
  ({ theme }) => `
  padding: ${theme.spacing(3)}px;
  border-top: 1px solid ${theme.palette.lighterGray};
  position: ${position ? position : 'sticky'};
  bottom: ${bottom ? bottom : 'inherit'}
  width: 100%;
`,
)

But this gives me a typescript error stating that position and bottom are not defined.

Upvotes: 0

Views: 2248

Answers (1)

Nishant
Nishant

Reputation: 55866

You have just added type annotations, and not really defined the new parameters in the function signature. Here is a better way to do this:

import styled from "styled-components";

export type FormFooterProps = {
  theme: any, //Use appropriate type
  position?: string,
  bottom?: string;
}
export const FormFooter = styled.div<FormFooterProps>(
  ({ theme, position = "sticky", bottom = "inherit" }) => `
  padding: ${theme.spacing(3)}px;
  border-top: 1px solid ${theme.palette.lighterGray};
  position: ${position};
  bottom: ${bottom}
  width: 100%;
`
);

Upvotes: 1

Related Questions