Search code examples
javascriptcssreactjsstyled-componentsemotion

React-Emotion: pass down defaultProps to in component reuse


I have this:

import styled from 'react-emotion';

const Box = styled('div')`
  display: flex;
  flex-direction: ${p => p.direction};
`;

Box.defaultProps = {
  direction: 'column'
};

This works just fine when I use the Box component. The default props are there as expected.

However, when I reuse Box with styled, the default props do not get passed down:

import styled from 'react-emotion';
import Box from './Box';

export const UniqResponsiveBox = styled(Box)`
  // some media queries and other new styles
`;

When I use UniqResponsiveBox, it does not have the defaultProps I declared for Box. The following workaround gets me thru, but seems redundant and I believe Im missing something that accomplishes this only using emotion.

import styled from 'react-emotion';

const BoxContainer = styled('div')`
  display: flex;
  flex-direction: ${p => p.direction};
`;

function Box(props) {
  return <BoxContainer {...props}/>
}

Box.defaultProps = {
  direction: 'column'
}

import styled from 'react-emotion';
import Box from './Box';

export const UniqResponsiveBox = styled(Box)`
  // some responsive queries and other uniq styles
`;

// In this scenario, the default props are there because I passed them explicitly. Helppp!


Solution

  • This particular issue is a bug inside Emotion - it was fixed in a pull request that was merged 11 days ago, so it should appear in the next release.

    In the meantime, another workaround to avoid the additional function would simply be:

    import styled from 'react-emotion';
    import Box from './Box';
    
    export const UniqResponsiveBox = styled(Box)`
      // some media queries and other new styles
    `;
    
    UniqResponsiveBox.defaultProps = Box.defaultProps