Skip to content

Instantly share code, notes, and snippets.

@pofulu
Last active August 31, 2023 09:21
Show Gist options
  • Save pofulu/6dc8ec687519184063dfcc5888c8b732 to your computer and use it in GitHub Desktop.
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
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