I found an example in Codepen https://codepen.io/dbilanoski/pen/LabpzG?editors=1010 of what I am wanting to do in my React Application. When I scroll down the the page it should highlight that section in my navbar, which is sticky at the top of the page. My app is a single page that contains about 5 to 6 sections that will be index/inline pages, so as the user scrolls down, it will take them to that next section. What approach should I take to incorporate this? More specifically, should I just use React, should I implement React Router Dom? What is the best approach to accomplish this functionality in the most general sense?
App
import React, {Component} from 'react';
import Footer from './components/footer/Footer';
import Hero from './components/hero/Hero';
import Resume from './components/resume/Resume';
import About from './components/about/About';
import Contact from './components/contact/Contact';
import Navbar from './components/navbar/Navbar';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
}
}
componentWillMount() {
window.addEventListener('scroll', this.navHighlighter);
}
navHighlighter() {}
render() {
return (
<div className="App">
<Navbar />
<Hero/>
<About/>
<Resume/>
<Contact/>
<Footer/>
</div>
);
}
}
Navbar
mport React, {Component} from 'react';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import { faBars } from '@fortawesome/free-solid-svg-icons'
import './navbar.css';
class Navbar extends Component {
constructor() {
super();
this.state = {
addClass: '',
showMenu: ''
}
this.handleScroll = this.handleScroll.bind(this);
this.toggleMenu = this.toggleMenu.bind(this);
}
componentDidMount() {
window.addEventListener("scroll", this.handleScroll)
}
handleScroll() {
if (window.scrollY > 0) {
this.setState({addClass: 'sticky'})
} else {
this.setState({addClass: ''})
}
}
toggleMenu() {
let { showMenu } = this.state;
this.setState({showMenu: showMenu === 'open' ? '' : 'open'})
}
render() {
return (
<div>
<header onScroll={this.handleScroll} className={this.state.addClass}>
<a href="#" className="logo">Jeremy</a>
<nav className={this.state.showMenu}>
<ul>
<li><a href="#" className="active">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#skills">Skills</a></li>
<li><a href="#projects">Projects</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
<div className="menu-toggle" onClick={this.toggleMenu}><FontAwesomeIcon className='icon' icon={faBars} /></div>
</header>
</div>
);
}
}
export default Navbar;