A guide for using Styled Components with Expo.
Styled Components is a CSS-in-JS solution that enables you to create React components with a given style very easily. Using styled-components
with Expo, you can create universal styles that'll work the same across web, mobile, and desktop!
Install the Styled Components package:
-
yarn add styled-components
Use styled-components/native
instead of styled-components
:
import React from 'react';
import styled from 'styled-components/native';
const Container = styled.View`
flex: 1;
background-color: #fff;
align-items: center;
justify-content: center;
`;
const Title = styled.Text`
color: #000;
text-align: center;
font-size: 16px;
`;
export default () => (
<Container>
<Title>Hello</Title>
</Container>
);
Usage with Next.js is a little different because we need to apply the React Native aliases manually, this can be done via @expo/webpack-config
(which is in @expo/next-adapter
).
@expo/next-adapter
to your project:-
npx @expo/next-adapter
-
yarn add -D babel-plugin-styled-components
1 | 1 | module.exports = { |
2 | 2 | presets: ['@expo/next-adapter/babel'], |
3 | plugins: [['styled-components', { ssr: true }]] | |
3 | 4 | }; |
styled-components/native
just like you would in a regular Expo project!Styled Components imports all of react-native-web
which breaks React Native web tree-shaking. This means your bundle size will be larger and include all of the components exported from react-native-web
.
Technically you can use styled-components
directly like this:
1 | import styled from 'styled-components/native'; | |
1 | import styled from 'styled-components'; | |
2 | 2 | |
3 | const Container = styled.View` | |
3 | const Container = styled(View)` | |
4 | 4 | background-color: #fff; |
5 | 5 | ` |
But doing this in the browser will throw the error: Warning: Using the "className" prop on <View> is deprecated.
.