0
votes

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!

2

2 Answers

1
votes

Would you try:

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

Another way which you could use and in my opinion would be much cleaner to read and thus maintainable is the following:

const getCorrectWidth = ({ expanded }) => (
  expanded
    ? 260
    : 80
);

const getCorrectSmallWidth = ({ expanded }) => (
  expanded
    ? '100%'
    : '20px'
);

const SideNavWrapper = styled.article`
  background: red;
  width: ${getCorrectWidth}px;

  ${media.smallScreen`
    background: yellow;
    width: ${getCorrectSmallWidth}
  `}
`;

The above has clear functions which tell the developer what they are doing. Syntax looks clean, also.