I am trying to use Bootstrap to expand and collapse the navbar when the hamburger icon is clicked. The issue is I am using React and I'm pretty sure Bootstrap's DOM manipulation is conflicting with React's DOM manipulation. So I'm trying to pull all the manipulation away from Bootstrap and rely purely on their styling and use React to update the classes instead. That feels like the correct way to me. Now I realize things like React Bootstrap exist but I already have vanilla Bootstrap integrated throughout my project and it appears like React Bootstrap is still on version 4, where I am using 5.
So as far as I can tell, Bootstrap is manipulating the classes on this div: <div id="navbarSupportedContent" style="" class="navbar-collapse collapse">
. So it appears that they are adding the class collapsing
and removing the class collapse
as the menu is expanding or collapsing. And then once it is fully shown, classes become navbar-collapse collapse show
and for collapsed: navbar-collapse collapse
.
The transition time is set to .35 seconds by Bootstrap. So here is my React code:
const handleNavCollapse = () => {
if (isNavCollapsed) {
setNavbarClasses('navbar-collapse collapsing');
//setTimeout( <-- I learned this way does not work correctly
setTimeout(() =>
setNavbarClasses('navbar-collapse collapse show'),
350
);
} else {
setNavbarClasses('navbar-collapse collapse');
}
setIsNavCollapsed(!isNavCollapsed);
};
Also, if this helps someone figure out an answer, here is the CSS that Bootstrap is applying with the collapsing
class:
.collapsing {
height: 0;
overflow: hidden;
transition: height 0.35s ease;
}
It works halfway in that it shows and hides the navbar menu correctly when clicking the hamburger icon. But there is no transition. I'm not seeing the collapsing
class get added when I watch the DOM in the inspector like I do on the Bootstrap site. I only see it add show
and remove show
. Maybe I'm not doing the setTimeout right.
Update: So I figured out from this SO answer: https://stackoverflow.com/a/42650143/571723 that I was in fact doing the setTimeout wrong. I switched to the arrow function. And now I see the collapsing
class getting added right away and then switching to show
after the 350ms timeout. Problem is there is still no transition animation, it merely shows the menu after 350ms.
Update 2: I'm getting further with my investigation into how Bootstrap is doing this. I have managed to take a screenshot of the console while Bootstrap was animating the navbar on their site.
So you can see the height set to a specific number
and that changes very quickly (actually that number does not change, it gets set to the 206px and stays there until it is fully opened). And you can also see height: 0
being overridden. Those things are not happening in my site in the inspector.