Passing in parameter to Styled Components

12,646

Solution 1

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

Use a function insead:

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:

top: ${(props) => props.topValue || 0}px;

Note: Doubled backticks are redundant.

Solution 2

You can pass an argument with Typescript as follows:

<StyledPaper open={open} />    

...

const StyledPaper = styled(Paper)<{ open: boolean }>`
   top: ${p => (p.open ? 0 : 100)}%;
`;
Share:
12,646
thadeuszlay
Author by

thadeuszlay

Updated on June 08, 2022

Comments

  • thadeuszlay
    thadeuszlay almost 2 years

    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.

  • thadeuszlay
    thadeuszlay over 5 years
    It seems like the custom value 123 didn't get passed through but the default value was accepted.
  • kind user
    kind user over 5 years
    @thadeuszlay It's not possible, actually :) If it doesn't work for you, just use ||.
  • Sam
    Sam about 3 years
    The type Paper makes this a bit more confusing I think, if you just replaced Paper with div would this work?
  • Jöcker
    Jöcker about 3 years
    I used Paper on purpose to make an example with a custom component. With a div would it work if you use styled.div<{ open: boolean }> instead.