Search code examples
expostyled-componentsreact-native-web

styled-components ThemeProvider breaks in React Native => Expo Web build


I’m working with a small expo project setup where I develop for both iOS/Android and Web. I recently wanted to add styled-components to the project and got everything up and running for Web and Mobile until I started working with a Theme Provider and the theme prop. I am 99% certain that I should have done everything correctly because it works for mobile but I get a JS exception in the web version.

  • I’ve created a type for the theme and I know it works because my IDE tells me when I try to add something wrong to the theme.
  • I’ve created a theme.ts and import it in the component where I’ve implemented the ThemeProvider. I know this works because when accessing prop.theme I get auto-completion and as I said it works on mobile.
const Container = styled.View`
    background-color: ${props => props.theme.color.primary};
`

This is the error I get: TypeError: Cannot read property ‘primary’ of undefined

I suspect it might have something to do with expo’s bundler and missing loaders or something? I don’t know. To my knowledge, I did everything as in the docs and suspect it is an issue with Expo Web and the ThemeProvider.

Those are the relevant packages I'm using:

"expo": "~39.0.2"
"styled-components": "^5.2.1"
"@babel/core": "~7.9.0"

I'm blocked by this because I need to decide whether to proceed with styled components or without them.


Solution

  • It turns out that when you import the ThemeProvider from "styled-components" and then work with "styled-components/native" that iOS and Android builds still work but web breaks...

    This was my error. Use "styled-components/native" everywhere! Stupid me