Skip to content

Instantly share code, notes, and snippets.

@ortense
Last active December 18, 2023 13:31
Show Gist options
  • Save ortense/230f49a3513d45c6ec71dc9f0d806934 to your computer and use it in GitHub Desktop.
Save ortense/230f49a3513d45c6ec71dc9f0d806934 to your computer and use it in GitHub Desktop.
Simple components for resposive layout in react
import { Box, VerticalStack, HorizontalStack, Center } from './Flex';
export function Example() {
return (
<Center
as="section"
style={{
backgroundColor: '#292929',
height: '100vh',
padding: '1rem',
}}
>
<VerticalStack as="article">
<VerticalStack>
<Box style={{ backgroundColor: 'lightblue' }}>lightblue</Box>
<Box style={{ backgroundColor: 'lightgreen' }}>lightgreen</Box>
<Box style={{ backgroundColor: 'lightcoral' }}>lightcoral</Box>
</VerticalStack>
<HorizontalStack>
<Box style={{ backgroundColor: 'turquoise' }}>turquoise</Box>
<Box style={{ backgroundColor: 'deeppink' }}>deeppink</Box>
<Box style={{ backgroundColor: 'violet' }}>violet</Box>
</HorizontalStack>
</VerticalStack>
</Center>
);
}
import { CSSProperties, HTMLAttributes, ReactNode } from 'react';
type Pretify<T> = {
[K in keyof T]: T[K];
} & {};
type FlexProps = {
as?: keyof JSX.IntrinsicElements;
direction?: CSSProperties['flexDirection'];
align?: CSSProperties['alignItems'];
justify?: CSSProperties['justifyContent'];
grow?: CSSProperties['flexGrow'];
gap?: CSSProperties['gap'];
children: ReactNode;
style?: CSSProperties;
} & HTMLAttributes<Omit<HTMLDivElement, 'style'>>;
export type BoxProps = Pretify<FlexProps>;
export type StackProps = Pretify<Omit<FlexProps, 'direction'>>;
export type CenterProps = Pretify<Omit<FlexProps, 'align' | 'justify'>>;
export function Box({
children,
direction = 'row',
align = 'flex-start',
justify = 'flex-start',
grow = '1',
gap = '0',
style = {},
as: Compoent = 'div',
}: BoxProps) {
const flexStyle: CSSProperties = {
display: 'flex',
flexDirection: direction,
alignItems: align,
justifyContent: justify,
gap,
flexGrow: grow,
width: '100%',
};
return <Compoent style={{ ...flexStyle, ...style }}>{children}</Compoent>;
}
export function HorizontalStack(props: StackProps) {
return <Box direction="row" {...props} />;
}
export function VerticalStack(props: StackProps) {
return <Box direction="column" {...props} />;
}
export function Center(props: CenterProps) {
return <Box align="center" justify="center" {...props} />;
}
export const Flex = {
Box,
HorizontalStack,
VerticalStack,
Center,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment