How to use data toggle collapse in Reactjs with Bootstrap?
Bootstrap menu toggle is a JS functionality. It's not a good idea to mix the JS part of Bootstrap with ReactJS, since both libraries manipulate the DOM and it can lead to bigger problems.
I suggest implementing the small functionality you need. Most of the menu toggle is just a class toggle thing.
import React, { Component } from "react";
export default class Menu extends Component {
constructor(props) {
super(props);
this.state = {
menu: false
};
this.toggleMenu = this.toggleMenu.bind(this);
}
toggleMenu(){
this.setState({ menu: !this.state.menu })
}
render() {
const show = (this.state.menu) ? "show" : "" ;
return (
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<a className="navbar-brand" href="/">Navbar</a>
<button className="navbar-toggler" type="button" onClick={ this.toggleMenu }>
<span className="navbar-toggler-icon"></span>
</button>
<div className={"collapse navbar-collapse " + show}>
<div className="navbar-nav">
<a className="nav-item nav-link active" href="/">Home <span class="sr-only">(current)</span></a>
<a className="nav-item nav-link" href="/">Features</a>
<a className="nav-item nav-link" href="/">Pricing</a>
<a className="nav-item nav-link" href="/">logout</a>
</div>
</div>
</nav>
);
}
}
There is an equivalent library called "react-bootstrap" that you can use to style your components the same way as you would use bootstrap https://react-bootstrap.github.io. This way you can follow react and bootstrap best practices without making unnecessary manipulations to do DOM which can sometimes bring unwanted side effects.