Simple react class toggle

in #steempress5 years ago


Original Article: https://baillieogrady.com/simple-react-class-toggle/



A simple react class toggle on scroll. Compared to the infamous jQuery, working with react can seem a little abstract at first but with aspects like the 'Virtual DOM' and 'State', I'm starting to realise why this library is really popular. After all, it's just a JavaScript library like jQuery is but with scalability built in mind, not to mention the constant community support it receives.

JS / JSX

import React from 'react'
import { Link } from 'gatsby'
import Menu from '../components/Menu'
import MenuItems from './MenuItems'
class Header extends React.Component {
state = { shadow: false }

toggleShadow = () => {
    let position = window.pageYOffset;
    console.log(position)
    if (position <= 20) {
        this.setState({
            shadow: false
        })
    } else {
        this.setState({
            shadow: true
        })
    }
}

componentDidMount = () => {
    window.addEventListener('scroll', this.toggleShadow);
}

render() {
    const shadowActive = this.state.shadow ? 'shadow-custom' : '';

    return (
        <header className={`header w-100 top-0 z-4 sticky ${shadowActive}`}>
            <div className="mw8 center ph3 pv3 flex justify-between items-center">
                <Link to="/" className="header__logo near-black no-underline ttu f5 b lh-solid font-family-heading logo">
                    BAILLIE
                </Link>
                <Menu toggle={menuActive}>
                    <MenuItems /> 
                </Menu>
            </div>
        </header>
    )
}

}
export default Header