Make sidebar slide in from the left when the button is clicked with TailwindCSS

Viewed 2598

There is a sidebar menu and a button which shows/hides the sidebar. The problem is that I don't know how to make it slide in from the left when it appears. Also to slide back to the right of the screen when it is closing.

Here is my code so far:

  const myClass = clsx({
    'transition duration-300 h-screen mt-5 fixed z-10 left-0 w-80 ': true,
    'opacity-0': open,
    'opacity-100': !open
  });
....

      return (
        <div className='w-8 h-8'>
          <button onClick={toggleSideBar}></button>
          <div className={containerClasses}>
            ...
          </div>
        </div>
      );

I guess it should be added something with respect to isOpened, when it is closed or opened, tried with Tailwind's transition property but it didn't work out.

2 Answers

Try adding the classes transition-all (docs) and some duration, e.g. duration-500. Then instead of manipulating opacity, manipulate the offset. Make your sidebar position absolute and add a negative left offset when not open (e.g. -left-36), and change it to left-0 when open.

Check out this live example where I'm sliding the sidebar when the page is hovered:

https://play.tailwindcss.com/BpHgqXmmYm

The idea writtten by @Szaman was helpful, here it is the solution for the above problem:

  const myClass = clsx({
    'transition-all duration-1000 h-screen mt-5 fixed z-10 ': true,
    '-left-80 w-80': open,
    'left-0 w-80': !open
  });
Related