Search code examples
cssreactjsmedia-queriesmixinsstyled-components

Use props to switch width using styled components mixins


Tech used - Styled components and react

I have a mixin to make my app responsive

import { css } from 'styled-components';

export default {
  smallScreen: (...args: any) => css`
    @media (max-width: 600px) {
      ${css(...args)}
    }
  `,
}

In another react component, I want to use the above defined method to write css that applied on small screens.

const SideNavWrapper = styled.article`
  background: red; // this works
  width: ${props => props.expanded ? '260px' : '80px'}; // this works

  ${media.smallScreen({
    background: 'yellow', // this works
    width: `${props => props.expanded ? '100%' : '20px'}`, // this doesn't work. props is undefined.
  })}
`;

Depending on props.expanded, I want to switch the width of SideNavWrapper. However it doesn't work on smaller screens. Background color changes as expected but not the width. On debugging, I realized that props is undefined. Any ideas what am I missing? Thank you so much!


Solution

  • Would you try:

    ${props => {
    return (media.smallScreen({
      background: 'yellow', 
      width: `${props.expanded ? '100%' : '20px'}`,
    }))
    }}