thadeuszlay
thadeuszlay

Reputation: 3015

Passing in parameter to Styled Components

How can I pass in an argument into Styled Components?

What I tried was to create an interface and a styled component:

export interface StyledContainerProps {
  topValue?: number;
}

export const StyledContainer: StyledComponentClass<StyledContainerProps> = styled.div`
  position: absolute;
  top: `${props.topValue || 0}px`;
`;

Then I want to use it like this:

<StyledContainer 
  topValue={123}
>
   This has a distance of 123px to the top
</StyledContainer>

But it's saying that props doesn't have the attribute topValue.

Upvotes: 19

Views: 38212

Answers (3)

kind user
kind user

Reputation: 41893

Actually you should receive cannot read property 'topValue' of undefined error.

Use a function insead:

const StyledContainer = styled.div<{ topValue: number }>`
    top: ${({ topValue = 0 }) => topValue}px;
`;

Also a little bonus - you can use argument destructuring and assign a default value for topValue if it doesn't exist (in your particular case - the default value would be 0).

However if you want to assign 0 in every case when topValue is falsy, use:

const StyledContainer = styled.div<{ topValue: number }>`
    top: ${(props) => props.topValue || 0}px;
`;

Note: Doubled backticks are redundant.

Upvotes: 23

omzer
omzer

Reputation: 1598

Let's assume you have a component that is called Avatar and you need to pass a boolean prop to decide the size of the conponent (40 or 80 pixels).

You define the styled component as follows:

export const UserAvatar = styled(Avatar)`
   height: ${props => (props.large ? 80 : 40)}px;
   width:  ${props => (props.large ? 80 : 40)}px;
`;

And you use it like this: <UserAvatar large="true" />

Upvotes: 3

J&#246;cker
J&#246;cker

Reputation: 6748

You can pass an argument with Typescript as follows:

<StyledPaper open={open} />    

...

const StyledPaper = styled(Paper)<{ open: boolean }>`
   top: ${p => (p.open ? 0 : 100)}%;
`;

Upvotes: 16

Related Questions