Last active
September 23, 2024 16:50
-
-
Save pofulu/6dc8ec687519184063dfcc5888c8b732 to your computer and use it in GitHub Desktop.
ZStack component for ChakarUI with React. It's works like ZStack in SwiftUI
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 { Grid, GridProps } from '@chakra-ui/react'; | |
import { FC } from 'react'; | |
export interface ZStackProps extends Omit<GridProps, 'justifyItems' | 'alignItems'> { | |
/** https://developer.apple.com/documentation/swiftui/alignment */ | |
alignment?: 'topLeading' | 'top' | 'topTrailing' | 'leading' | 'center' | 'trailing' | 'bottomLeading' | 'bottom' | 'bottomTrailing'; | |
} | |
export const ZStack: FC<ZStackProps> = ({ alignment = 'center', ...props }) => { | |
const justifyItems = (() => { | |
switch (alignment) { | |
case 'topLeading': case 'leading': case 'bottomLeading': return 'start'; | |
case 'topTrailing': case 'trailing': case 'bottomTrailing': return 'end'; | |
default: return 'center'; | |
} | |
})(); | |
const alignItems = (() => { | |
switch (alignment) { | |
case 'topLeading': case 'top': case 'topTrailing': return 'start'; | |
case 'bottomLeading': case 'bottom': case 'bottomTrailing': return 'end'; | |
default: return 'center'; | |
} | |
})(); | |
// https://codepen.io/everdimension/pen/BaNpeWe | |
return <Grid css={{ alignItems, justifyItems, '*': { gridArea: '1/1/1/1' } }} {...props}> {props.children}</Grid>; | |
}; | |
// Usage | |
// This should draw the similar result like: https://developer.apple.com/documentation/swiftui/zstack | |
function Example() { | |
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] | |
return ( | |
<ZStack> | |
{colors.map((color, index) => | |
<Box | |
key={index} | |
bgColor={color} | |
boxSize='100px' | |
transform={`translate(${10 * index}px, ${10 * index}px)`} | |
/> | |
)} | |
</ZStack> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment