Published on

How to Pass Parameters to Styled Components in React

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Pass Parameters to Styled Components in React

Styled Components allow for dynamic styling in React applications. However, passing props to Styled Components requires a specific approach. In this guide, we will explore different ways to pass parameters and use them effectively.

1. Passing Props in Styled Components (JavaScript)

In JavaScript, you can pass props to a Styled Component like this:

import styled from 'styled-components'

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

export default function App() {
  return <StyledContainer topValue={123}>This has a distance of 123px to the top</StyledContainer>
}

This approach uses a function inside the template literal to access the topValue prop and apply it dynamically.

2. Using TypeScript for Typed Props

If you're using TypeScript, you should define the prop types explicitly:

import styled from 'styled-components';

interface StyledContainerProps {
  topValue?: number;
}

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

export default function App() {
  return (
    <StyledContainer topValue={123}>
      This has a distance of 123px to the top
    </StyledContainer>
  );
}

3. Boolean Props in Styled Components

If you need to toggle styles based on a boolean prop, you can do this:

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

export default function App() {
  return <StyledPaper open={true}>I'm a Styled Paper</StyledPaper>;
}

4. Conditional Styling Using Props

For more complex conditions, you can pass props like this:

const UserAvatar = styled.div<{ large?: boolean }>`
  height: ${({ large }) => (large ? 80 : 40)}px;
  width: ${({ large }) => (large ? 80 : 40)}px;
`;

export default function App() {
  return <UserAvatar large={true} />;
}

Conclusion

Passing parameters to Styled Components in React is a powerful way to create dynamic styles. You can:

  • Use functions inside template literals to apply props dynamically.
  • Define TypeScript interfaces for better type safety.
  • Use boolean props to toggle styles.
  • Apply conditional styles based on different prop values.

FAQs

1. Can I pass multiple props to a Styled Component?

Yes, you can pass multiple props by defining them in the styled function and using them within the CSS rules.

2. How do I apply default values to props?

You can use default values in destructuring like ({ topValue = 0 }) inside the styled component.

3. Is it better to use TypeScript with Styled Components?

Yes, TypeScript improves type safety and prevents runtime errors by ensuring the correct prop types are passed.