Can styled-components and react-redux connect, withTheme HOC be used together without this bad workaround?

Viewed 482

We're attempting to upgrade a codebase from styled-components v3 to v4/5. A pattern we were using no longer seems to work, despite it seeming like it should.

The pattern (in pseudocode):

// In reusable component file

const LeafComponent = (props) => whatever
const StyledLeafComponent = styled(LeafComponent)` styles which might reference connect props here `
const ReusableComponent = connectOrWithTheme(StyledLeafComponent)

// In some other file where the reusable component is being customized

const CustomizedComponent = styled(ReusableComponent)` additional context-specific styles here `

In v4 and v5, this pattern fails for both connect() and withTheme, with the corresponding props (either store props, or theme), being undefined in the reusable component (props from connect() are also undefined in the leaf component's styles, where we might need to reference them). In fact, mapStateToProps in connect() doesn't seem to even run at all!

The following workaround which just adds a pass-through component in between seems to fix things:

const CustomizedComponent = styled(props => <ReusableComponent {...props} />)` additional context-specific styles here `

But the problem with this workaround is that it's easy to accidentally omit and introduce sneaky runtime errors, not to mention that the codebase we're upgrading becomes a minefield of possible runtime errors until we do a thorough review of every usage of styled-components that we have along with connect, withTheme, and possibly other similar HOCs (which is a lot). (We're using TypeScript, so compiler errors would be valuable).

Obviously the best solution would be to get this fixed in styled-components itself, but that doesn't seem likely at this point. We've been spending months trying to get a better answer than this, filing an issue against the styled-components repo on GitHub and reaching out in Spectrum. We have a simple and clear reproduction of the issue on codesandbox:

No responses.

Is there a better workaround than the one above? Or is that what we're stuck with? Are we misguided in using this pattern in the first place, and should be doing something else? Surely styled-components, react, and redux are all popular libs and are being used together by many. This has to have been encountered and solved before.

0 Answers
Related