jeudi 8 avril 2021

Menu Opened/Closed States Inherited in Children with Staggered Transitions in Tailwind/React

I'm struggling to figure out how to code a header/menu in my React/Tailwind app.

Here are the requirements:

  • Header contains two sub-sections: Primary navigation and secondary navigation.
  • On desktop the primary navigation is on the left, and the secondary navigation is on the right.
  • On mobile the header contains a hamburger menu that contains both the primary and secondary navigation.
  • When this hamburger menu opens each navigation item appears with a staggered transition-delay.

What is the cleanest/most elegant approach to implement this with Tailwind?

I thought about separating Header/Navigation/NavigationItem into their own components, but the issue with this is that the Header needs to be aware of the NavigationItem components so that it can pass a isMenuOpen parameter to tell them to animate-in/out when the menu opens/closes.

It looks like this:

const App = () => {
  const [isMenuOpen, setIsMenuOpen] = useState(false)

  const handleMenuToggle = (isMenuOpen) => {
    setIsMenuOpen(isMenuOpen)
  }

  return (
    <Header onMenuToggle={handleMenuToggle}>
      <Navigation appearance="primary">
        <NavigationItem appearance="primary" index={0} isMenuOpen={isMenuOpen}>
          Menu Item #1
        </NavigationItem>
        <NavigationItem appearance="primary" index={1} isMenuOpen={isMenuOpen}>
          Menu Item #2
        </NavigationItem>
        <NavigationItem appearance="primary" index={2} isMenuOpen={isMenuOpen}>
          Menu Item #3
        </NavigationItem>
        <NavigationItem appearance="primary" index={3} isMenuOpen={isMenuOpen}>
          Menu Item #4
        </NavigationItem>
      </Navigation>
      <Navigation appearance="secondary">
        <NavigationItem appearance="secondary" index={4} isMenuOpen={isMenuOpen}>
          Facebook
        </NavigationItem>
        <NavigationItem appearance="secondary" index={5} isMenuOpen={isMenuOpen}>
          Twitter
        </NavigationItem>
      </Navigation>
    </Header>
  )
}

This isn't elegant and the components are too heavily tied to each other.

Another option was to do it purely in CSS with a class like .header.is-open .navigation-item {} but this feels like it goes against the Tailwind patterns.

Is there another way to do this?

Aucun commentaire:

Enregistrer un commentaire