DEV Community

Cover image for React Drawer like a Champ!
Alex Suarez
Alex Suarez

Posted on

React Drawer like a Champ!

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!


import React from 'react'
import { Box } from '../../structural'
import { directions } from './directions'

export default function Drawer({
  isOpen = false,
  speed = 0.5,
  width = '100vw',
  height = '100vh',
  bgColor = 'white',
  direction = 'right',
  zIndex = 99,
}: DrawerProps) {
  return (
      boxShadow='0 0 15px 3px rgba(0, 0, 0, 0.1)'
        transition: `all ${speed}s ease`,

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'

Enter fullscreen mode Exit fullscreen mode

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%'

Enter fullscreen mode Exit fullscreen mode


Now? You know how to build a Drawer that opens from every side of your window! :)

Top comments (2)

longvd89 profile image

What is box component

alexandprivate profile image
Alex Suarez

Hi it's a simple component styled with styled components and styled system that's exposes some css properties as props, you can simple use a div and move this values I set via props in the style object, for more info you may look at sorry for the confusion :)