Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
styled-components integration
{
"useScreenRem": {
"prefix": "rem",
"body": [
"${({ theme }) => theme.screen.rem(${1:})}px;",
],
"description": "Use rem helper function from responsive native"
}
}
import 'styled-components';
import type { ResponsiveTheme } from '../ThemeProvider';
import { YourThemeType } from '../theme';
declare module 'styled-components' {
export interface DefaultTheme extends ResponsiveTheme, YourThemeType {}
}
import React, { useMemo } from 'react';
import {
useScreen,
ScreenContextData,
MediaQuery,
BreakpointValues,
rem,
getNearestBreakpointValue,
validateMediaQuery
} from 'responsive-native';
import {
ThemeProvider as StyledThemeProvider,
} from 'styled-components';
type Query = Omit<MediaQuery, 'currentBreakpoint'>;
type Screen = Pick<ScreenContextData, 'breakpoint' | 'padding'> & {
breakpointValue<T = unknown>(
values: BreakpointValues,
): T | undefined;
mediaQuery(query: Query): boolean;
rem(size: number, shouldScale?: boolean): number;
};
export interface ResponsiveTheme {
screen: Screen;
}
interface Props {
children?: React.ReactNode;
}
export function ThemeProvider ({children}: Props) {
const { breakpoint, padding, baseFontSize, fontScaleFactor } = useScreen();
const theme = useMemo(() => {
return {
// ...yourTheme
screen: {
breakpoint,
padding,
rem: (size: number, shouldScale?: boolean) => {
return rem({
size,
shouldScale,
baseFontSize,
fontScaleFactor
})
},
breakpointValue: (values: BreakpointValues) => {
return getNearestBreakpointValue({
breakpoint: breakpoint.size,
values
})
} ,
mediaQuery: ({ minBreakpoint, maxBreakpoint, platform }: Query) => {
return validateMediaQuery({minBreakpoint, maxBreakpoint, platform, currentBreakpoint: breakpoint.size})
}
}
}
}, [breakpoint, padding, baseFontSize, fontScaleFactor])
return (
<StyledThemeProvider theme={theme}>
{children}
</StyledThemeProvider>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment