Skip to content

Instantly share code, notes, and snippets.

@wildseansy
Last active August 11, 2022 01:23
Show Gist options
  • Save wildseansy/db98e35f276cb90535d48a16662d1c44 to your computer and use it in GitHub Desktop.
Save wildseansy/db98e35f276cb90535d48a16662d1c44 to your computer and use it in GitHub Desktop.
Sample React Native Styled Components App
// App.tsx
import { ThemeProvider } from "styled-components";
export const App: React.FC<{children: React.ReactNode}> = ({children}) => {
return (
<ThemeProvider theme={theme}>
{children}
</ThemeProvider>
)
}
import React from "react"
import { Text, View } from "react-native"
// Import from YOUR styled extension, if you want type completion
import styled, { css } from "@src/styled";
type Props = {
size: "large" | "small"
};
// Integrate a style pattern into other components' styles
const boxShadow = css`
box-shadow: 0px 4px ${({theme}) => theme.space.md}px rgba(0, 0, 0, 0.2);
`;
const Container = styled.View<Props>`
flex: 1;
background-color: ${({theme}) => theme.colors.blue1};
padding: ${({theme, size}) => size === "large" ? theme.space.lg : theme.space.sm}px;
${boxShadow}
`;
export const ExampleComponent = () => {
return (
<Container size="large">
<Text>Hello World</Text>
</Container>
)
}
// @src/styled.ts
import * as styledComponents from "styled-components/native";
export const theme = {
colors: {
blue2: "#007EF2",
blue1: "#CCDFF1",
red2: "#FF550C",
red1: "#F9CDBA",
yellow2: "#FAA82D",
yellow1: "#FFC702",
white: "#FFFFFF",
black: "#000000",
},
fontSizes: {
p: 12,
h4: 14,
h3: 18,
h2: 20,
h1: 24
},
space: {
sm: 2,
md: 4,
lg: 8
}
};
// You may end up having to manually specify the type of the theme, depending on how you import it.
type MyTheme = typeof theme
const {
default: styled,
css,
ThemeProvider,
} = styledComponents as styledComponents.ReactNativeThemedStyledComponentsModule<MyTheme>;
export { css };
export default styled;
import { ThemeContext } from "styled-components";
export const ThemeAccessComponent = () => {
// If you need to access theme directly:
const theme = React.useContext(ThemeContext);
return (
<View style={{ padding: theme.space.lg }} />
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment