DEV Community

Farai Bvuma
Farai Bvuma

Posted on

Dynamic Styling with Props in Styled-Components

Introduction

Have you ever been stuck trying to figure out how to manipulate the styles of a prop in React using styled-components? What about when you want to directly apply CSS rules based on a prop's value, even if that prop is not a standard CSS property? Here is a quick guide on how you can get this done.

Let's say that you have a button component with a prop called state(isLoading, isActive etc), and you want to change how this React component is displayed based on whether the state is true or false. Simply follow the below example, swapping out the CSS rules that you wish to conditionally apply. We are using TypeScript and styled-components in the below example.

const StyledComponent = styled.button<{ state?: boolean }>`
   // The base CSS styles for the button go here
   background-color: blue;

   // Styles will be conditionally applied based on the 'state' prop
   ${({ state }) => state && `
    // These CSS rules will apply only when the 'state' prop is true
    border: 1px solid darkblue;
    opacity: 0.8;
  `}
`;
Enter fullscreen mode Exit fullscreen mode

How it works

Since state is not a CSS property(like color or padding), we use a JavaScript template literal( ${} ) to inject our custom logic directly into the CSS.

Inside the template literal, we provide a callback function(({ state }) => ... ) that is used by styled-components to pass the component's props. We have also used object destructuring( {state} ) to easily access the prop's value.

As previously mentioned, the aim is to conditionally render the button based on the state prop, and we do this by using the logical AND operator( && ), where if the state prop is truthy, the expression evaluates to the CSS string inside of the inner backticks, with styled-components proceeding to apply the CSS. Otherwise, if the state prop is falsy, no CSS is injected from the block.

Conclusion

Using this pattern to conditionally render components in React based on values of props is a great way to create dynamic components. Be sure to give it a try.

Top comments (0)