Last active
September 20, 2021 08:32
-
-
Save HeavenOSK/18bdda3e657f27bd038a23b3659b1daf to your computer and use it in GitHub Desktop.
Switch components responsively with Chakra UI display props
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { ReactNode } from 'react' | |
import { BoxProps, chakra } from '@chakra-ui/react' | |
import { ResponsiveObject } from '@chakra-ui/styled-system/dist/types/utils/types' | |
type ResponsiveItems = ResponsiveObject<ReactNode> | |
type Props = { | |
items: ResponsiveItems | |
} & BoxProps | |
const breakpoints = ['base', 'sm', 'md', 'lg', 'xl', '2xl'] | |
const ChakraDiv = chakra('div') | |
const ResponsiveComponent = (props: Props) => { | |
const effectiveBPs = breakpoints | |
.map(p => { | |
return props.items[p] ? p : null | |
}) | |
.filter(p => p !== null) | |
return ( | |
<> | |
{effectiveBPs.map(p => { | |
if (!p || !props.items[p]) { | |
return <></> | |
} | |
const displayConfig = { | |
base: 'none', | |
[p]: 'block', | |
} | |
const indexP = effectiveBPs.indexOf(p) | |
if (indexP < effectiveBPs.length - 1) { | |
const nextBP = effectiveBPs[indexP + 1] | |
displayConfig[nextBP!] = 'none' | |
} | |
return ( | |
<ChakraDiv {...(props as BoxProps)} key={p} display={displayConfig}> | |
{props.items[p]} | |
</ChakraDiv> | |
) | |
})} | |
</> | |
) | |
} | |
export default ResponsiveComponent |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage