Alex Suarez
Posted on November 7, 2020
Hi there!!! Hope everything goes fine with you on the other side of the screen wherever you are!
I just found out today about this amazing app for VSCode (Thanks to Cody, the master of Tests!), CodeSpan, and man! I can't hold myself so I decided to write an article with some cool screenshots taken with this app, and what a better example to show than a drawer that I'm building from scratch for the latest component library I'm building!
Here we go...
Oh, wait I'm using TS and styled-system to build this out so "Box" component may look a little weird, if I don't, let you know about this. Now ... here we go ...
React Component!
So nothing fancy here, just a Box component with some props, typed by this interface right here
What is missing? The direction and that is where the magic is ...
So with the helper from above you and based on the isOpen prop you can translate your drawer from the selected direction using the direction props spreading the helper in the component style like this ...
So that's it ... Or since I've always hated those dev who share only images... here is your code!
Component
import React from 'react'
import { Box } from '../../structural'
import { directions } from './directions'
export default function Drawer({
children,
isOpen = false,
speed = 0.5,
width = '100vw',
height = '100vh',
bgColor = 'white',
direction = 'right',
zIndex = 99,
className,
style
}: DrawerProps) {
return (
<Box
className={className}
position='fixed'
height={height}
width={width}
backgroundColor={bgColor}
zIndex={zIndex}
boxShadow='0 0 15px 3px rgba(0, 0, 0, 0.1)'
style={{
transition: `all ${speed}s ease`,
...directions(isOpen)[direction],
...style
}}
data-testid='drawer'
>
{children}
</Box>
)
}
export interface DrawerProps {
children?: React.ReactNode
isOpen?: boolean
speed?: number
width?: number | string
height?: number | string
bgColor?: string
zIndex?: number
direction?: 'top' | 'left' | 'right' | 'bottom'
}
Direction helper
export const directions = (isOpen: boolean) => ({
right: {
transform: isOpen ? 'translateX(-100%)' : 'translateX(100%)',
top: 0,
left: '100%'
},
left: {
transform: isOpen ? 'translateX(100%)' : 'translateX(-100%)',
top: 0,
right: '100%'
},
top: {
transform: isOpen ? 'translateY(100%)' : 'translateY(-100%)',
left: 0,
bottom: '100%'
},
bottom: {
transform: isOpen ? 'translateY(-100%)' : 'translateY(100%)',
left: 0,
top: '100%'
}
})
Now
Now? You know how to build a Drawer that opens from every side of your window! :)
Posted on November 7, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.