Search code examples
cssreactjstailwind-cssdropdownnavbar

Navbar in React and Tailwind CSS


I have a task to create a navbar with two dropdowns on hover using Tailwind css. I have read the Tailwind documentation regarding hover, focus etc. I have tried using groups and group modifiers but couldn't get it to work.

So I decided to ask you guys for some directions and help if possible. How would you approach this?

Below is the code I am currently working with:

`

    {/*First button - Resources */}
    <div className='flex item-center flex-col justify-center m-5 relative group'>
        <button className='p-3 text-sm hover:bg-slate-400'>Resources</button>

      <div className='group-hover: block'>
        <ul className='mt-2 flex flex-col items-center justify-center'>
            <li><a href='#'>New Starter</a></li>
            <li><a href='#'>Stakeholders</a></li>
            <li><a href='#'>Checklists</a></li>
        </ul>

      </div>
        
    </div>

    {/*Second button - Tools */}

    <div className='flex item-center flex-col justify-center relative group'>
        <button className='p-3 text-sm hover:bg-slate-400'>Tools</button>

      <div className='group-hover: block'>
        <ul className='mt-2 flex flex-col items-center'>
            <li><a href='#'>TIE</a></li>
            <li><a href='#'>Asset manager</a></li>
            <li><a href='#'>PM</a></li>
        </ul>

      </div>
        
    </div>


</div>`

Solution

    • You'd want no space between group-hover: and block – you'd want group-hover:block.
    • The element that you're applying group-hover:block to already has display: block by default so this has no effect. Typical dropdown elements are not visible in their default state, so consider applying display: none via the hidden class.

    Putting it all together:

    <script src="https://cdn.tailwindcss.com"></script>
    
    <div class='flex item-center flex-col justify-center m-5 relative group'>
      <button class='p-3 text-sm hover:bg-slate-400'>Resources</button>
    
      <div class='hidden group-hover:block'>
        <ul class='mt-2 flex flex-col items-center justify-center'>
          <li><a href='#'>New Starter</a></li>
          <li><a href='#'>Stakeholders</a></li>
          <li><a href='#'>Checklists</a></li>
        </ul>
    
      </div>
    
    </div>
    
    <div class='flex item-center flex-col justify-center relative group'>
      <button class='p-3 text-sm hover:bg-slate-400'>Tools</button>
    
      <div class='hidden group-hover:block'>
        <ul class='mt-2 flex flex-col items-center'>
          <li><a href='#'>TIE</a></li>
          <li><a href='#'>Asset manager</a></li>
          <li><a href='#'>PM</a></li>
        </ul>
    
      </div>
    
    </div>