Skip to content

Commit

Permalink
Merge pull request #202 from ChariseWalraven/master
Browse files Browse the repository at this point in the history
Replace DOM manipulation in Navbar with State and Class Method
  • Loading branch information
ZoltanVeres authored Mar 8, 2019
2 parents fd19cad + c9f882a commit f89b8ab
Showing 1 changed file with 43 additions and 31 deletions.
74 changes: 43 additions & 31 deletions src/components/Navbar.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,37 @@
import React from 'react'
import { Link } from 'gatsby'
import github from '../img/github-icon.svg'
import logo from '../img/logo.svg'
import React from "react";
import { Link } from "gatsby";
import github from "../img/github-icon.svg";
import logo from "../img/logo.svg";

const Navbar = class extends React.Component {
componentDidMount() {
// Get all "navbar-burger" elements
const $navbarBurgers = Array.prototype.slice.call(
document.querySelectorAll('.navbar-burger'),
0
)
// Check if there are any navbar burgers
if ($navbarBurgers.length > 0) {
// Add a click event on each of them
$navbarBurgers.forEach(el => {
el.addEventListener('click', () => {
// Get the target from the "data-target" attribute
const target = el.dataset.target
const $target = document.getElementById(target)

// Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu"
el.classList.toggle('is-active')
$target.classList.toggle('is-active')
})
})
}
constructor(props) {
super(props);
this.state = {
active: false,
navBarActiveClass: ""
};
}

toggleHamburger = () => {
// toggle the active boolean in the state
this.setState(
{
active: !this.state.active
},
// after state has been updated,
() => {
// set the class in state for the navbar accordingly
this.state.active
? this.setState({
navBarActiveClass: "is-active"
})
: this.setState({
navBarActiveClass: ""
});
}
);
};

render() {
return (
<nav
Expand All @@ -37,16 +42,23 @@ const Navbar = class extends React.Component {
<div className="container">
<div className="navbar-brand">
<Link to="/" className="navbar-item" title="Logo">
<img src={logo} alt="Kaldi" style={{ width: '88px' }} />
<img src={logo} alt="Kaldi" style={{ width: "88px" }} />
</Link>
{/* Hamburger menu */}
<div className="navbar-burger burger" data-target="navMenu">
<div
className={`navbar-burger burger ${this.state.navBarActiveClass}`}
data-target="navMenu"
onClick={() => this.toggleHamburger()}
>
<span />
<span />
<span />
</div>
</div>
<div id="navMenu" className="navbar-menu">
<div
id="navMenu"
className={`navbar-menu ${this.state.navBarActiveClass}`}
>
<div className="navbar-start has-text-centered">
<Link className="navbar-item" to="/about">
About
Expand Down Expand Up @@ -79,8 +91,8 @@ const Navbar = class extends React.Component {
</div>
</div>
</nav>
)
);
}
}
};

export default Navbar
export default Navbar;

0 comments on commit f89b8ab

Please sign in to comment.