4

I have a simple HeadlessUI Tab component like the one below.

import { Tab } from '@headlessui/react'

function MyTabs() {
  return (
    <Tab.Group>
      <Tab.List>
        <Tab>Tab 1</Tab>
        <Tab>Tab 2</Tab>
        <Tab>Tab 3</Tab>
      </Tab.List>
      <Tab.Panels>
        <Tab.Panel>Image content 1</Tab.Panel>
        <Tab.Panel>Image content 2</Tab.Panel>
        <Tab.Panel>Image content 3</Tab.Panel>
      </Tab.Panels>
    </Tab.Group>
  )
}

I would like to smoothly change the view (in this case, each Tab.Panel content) when I click the tab menu. When I looked into the official example, there was no description of how to handle the transition like fade-in.

I know there is a tailwind fade-in & delay & transition animation CSS tag, but I am unsure where to add that tag so the headlessUI Tabs work smoothly.

Any code example is appreciated!

husky
  • 831
  • 3
  • 10
  • 24

1 Answers1

0

Use transitions provided from headlessui:

import { Transition } from '@headlessui/react'

Example:

import { Transition } from '@headlessui/react'
import { useState } from 'react'

function MyComponent() {
  const [isShowing, setIsShowing] = useState(false)

  return (
    <>
      <button onClick={() => setIsShowing((isShowing) => !isShowing)}>
        Toggle
      </button>
      <Transition
        show={isShowing}
        enter="transition-opacity duration-75"
        enterFrom="opacity-0"
        enterTo="opacity-100"
        leave="transition-opacity duration-150"
        leaveFrom="opacity-100"
        leaveTo="opacity-0"
      >
        I will fade in and out
      </Transition>
    </>
  )
}

Animating transitions

By default, a Transition will enter and leave instantly, which is probably not what you're looking for if you're using this component.

To animate your enter/leave transitions, add classes that provide the styling for each phase of the transitions using these props:

  • enter: Applied the entire time an element is entering. Usually you define your duration and what properties you want to transition here, for example transition-opacity duration-75.

  • enterFrom: The starting point to enter from, for example opacity-0 if something should fade in.

  • enterTo: The ending point to enter to, for example opacity-100 after fading in.

  • leave: Applied the entire time an element is leaving. Usually you define your duration and what properties you want to transition here, for example transition-opacity duration-75.

  • leaveFrom: The starting point to leave from, for example opacity-100 if something should fade out.

  • leaveTo: The ending point to leave to, for example opacity-0 after fading out.

Reference : Create top-down slide animation using `Transition` from `@headlessui/react` using Tailwind CSS

krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88