Fixed vs Dynamic Nav Links Menu Toggle Styling in React

Published: (January 14, 2026 at 01:48 PM EST)
2 min read
Source: Dev.to

Source: Dev.to

Fixed Height Approach

In this approach, we set a fixed height when the menu is opened. This method works well when you know the menu’s height in advance.

import { useState } from 'react';
import { FaBars } from 'react-icons/fa';
import { links } from './data';

const Navbar = () => {
  const [showLinks, setShowLinks] = useState(false);

  return (
    
       setShowLinks(!showLinks)}>
        
      

      
        

          {links.map(link => (
            
              {link.text}
            
          ))}
        

      
    
  );
};

export default Navbar;
.links-container {
  height: 0;
  overflow: hidden;
  transition: height 250ms ease-in-out;
}

.links-container.open {
  height: 10rem; /* Adjust as needed */
}

In this example, the menu container’s height is set to 0 by default, and when the menu is opened, the height is set to 10rem.

Dynamic Height Approach

The dynamic height approach automatically adjusts the menu’s height based on its content. It’s a great choice if you have a variable number of items.

import { useState, useRef } from 'react';
import { FaBars } from 'react-icons/fa';
import { links } from './data';

const Navbar = () => {
  const [showLinks, setShowLinks] = useState(false);
  const linksRef = useRef(null);

  const linksContainerStyles = {
    height: showLinks ? `${linksRef.current?.offsetHeight}px` : 0,
  };

  return (
    
       setShowLinks(!showLinks)}>
        
      

      
        

          {links.map(link => (
            
              {link.text}
            
          ))}
        

      
    
  );
};

export default Navbar;
.links-container {
  overflow: hidden;
  transition: height 250ms ease-in-out;
}

In this case, the height is dynamically calculated based on the content inside the menu. When the menu is opened, its height adjusts to fit the content.

Key Differences

  • Fixed Height: The height is set manually and doesn’t change unless you update it. It’s simple but less flexible.
  • Dynamic Height: The height adjusts automatically based on the content. It’s more flexible but slightly more complex.

Conclusion

Both methods are great for different use cases. If your menu has a fixed number of items, use the fixed height approach. If the number of items may change or you want more flexibility, go with the dynamic height approach.

Credits: John Smilga’s course

Back to Blog

Related posts

Read more »

Learning with freeCodeCamp

So the New Year brought some changes and, hopefully, commitments. I joined the DEV Community and also created a new account on freeCodeCamp, starting with versi...