Reputation: 528
Edit: Figured it out. I updated the answer at the bottom
So I figured out how to change my class to active whenever I click on my icon, but I'm not sure how I'd change it to false whenever I click it again?
class NavbarItems extends Component {
state = { clicked: false}
handleClick = () => {
this.setState({ clicked: true })
}
render() {
return (
<nav className="NavbarItems">
<h1 className="navbar-logo">Startup</h1>
<div className='menu-icon' onClick={this.handleClick}>
<i class="fas fa-bars"></i>
</div>
<ul className={this.state.clicked ? 'nav-menu active' : 'nav-menu'}>
How would I change the ul className back to 'nav-menu' after I clicked on the menu icon?
Right now when I click on it, it adds the active class, but I don't know how to remove that active class whenever I click again
handleClick = () => {
this.setState(clicked => (
{ clicked: !clicked.clicked }
))
}
Upvotes: 0
Views: 1025
Reputation: 620
Use classnames https://www.npmjs.com/package/classnames
npm install classnames --save
In your component
import cx from 'classnames';
class NavbarItems extends Component {
state = { clicked: false}
handleClick = () => {
this.setState({ clicked: !this.state.clicked })
}
render() {
return (
<nav className="NavbarItems">
<h1 className="navbar-logo">Startup</h1>
<div className='menu-icon' onClick={this.handleClick}>
<i class="fas fa-bars"></i>
</div>
<ul className={cx('nav-menu', {['active']: this.state.clicked})}>
Upvotes: 0
Reputation: 1539
Change your handleClick to this:
handleClick = () => {
this.setState(prevState => ({
clicked: !prevState.clicked
}))
}
Upvotes: 1
Reputation: 123
This should do the trick
handleClick = () => {
this.setState({ clicked: !this.state.clicked });
};
Upvotes: 0