Active classnames in menu on a one-page website using GatsbyJS

Active classnames in menu on a one-page website using GatsbyJS

Related searches

I'm using a single page template with GatsbyJS on which the menu scrolls to the different sections of the same page (#home, #about, #portfolio, etc). Is there a way to set an active classname on the links, highlighting the link the user is on?


You can set the activeStyle or activeClassName prop to add styling attributes to the rendered element when it matches the current URL, and Gatsby also supports React Router's props exact, strict, isActive, and location. If any of these props are set, then React Router's NavLink component will be used instead of the default Link.

Example:

import Link from "gatsby-link"

render () {
 <div>
  <Link
   to="/another-page/"
   activeStyle={{
     color: 'red'
   }}
   innerRef={(el) => { this.myLink = el }}
  >
   Another page
  </Link>
 </div>
}

Visit https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-link

Gatsby Link API, Gatsby's <Link> component enables linking to internal pages as well as a powerful performance feature called All props are passed through to @reach/​router's Link component. Show active styles for partially matched and parent links will start with exactly one slash, and that anything else is external. 1 Active classnames in menu on a one-page website using GatsbyJS Dec 19 '19 0 How to reduce spacing between columns in a 7 grid Bootstrap page Feb 20 '19 0 I want My form button to appear in one single line with other buttons Nov 5 '18


I did it the hard way as I couldn't find another solution:

import React, { Component } from 'react';
import './Menu.css';

class Menu extends Component {

    constructor(props) {
        super(props)
        this.state = {
            home: true,
            about: false,
            portfolio: false
        }
        this.handleActive = this.handleActive.bind(this)
    }

    handleActive(button) {
        switch (button) {
            case 'home':
                this.setState({
                    home: true,
                    about: false,
                    portfolio: false
                });
                break;
            case 'about':
                this.setState({
                    home: false,
                    about: true,
                    portfolio: false
                });
                break;
            case 'portfolio':
                this.setState({
                    home: false,
                    about: false,
                    portfolio: true
                });
                break;
            default: break;
        }
    }

    render() {
        return (
            <div id="nav-wrap">
                <nav>
                    <input type="checkbox" id="checkbox1" />
                    <label htmlFor="checkbox1">
                        <ul className="menu first">
                            <li><a
                                className={this.state.home ? 'active' : null}
                                onClick={() => this.handleActive('home')}
                                href="#home">HOME</a></li>
                            <li><a
                                className={this.state.about ? 'active' : null}
                                onClick={() => this.handleActive('about')}
                                href="#about">ABOUT МЕ
            </a></li>
                            <li><a
                                className={this.state.portfolio ? 'active' : null}
                                onClick={() => this.handleActive('portfolio')}
                                href="#portfolio">PORTFOLIO</a></li>
                        </ul>
                        <span className="toggle">☰</span>
                    </label>
                </nav>

            </div>
        )
    }
}

export default Menu;

How To Build a Static Site With Gatsby.js, static website generators. If you want to use React to build your static website, Gatsby could… Also, multiple page queries have to be made in one file and you pipe them all to templates in the same file. <div className="dropdown-​menu" aria-labelledby="navbarDropdown"> "active" : ""}`} key={p}> From WordPress to Developing in React — Starting to See It As a frontend designer I’ve always prided myself on being a HTML and CSS specialist. My use of JavaScript has been limited to animations and DOM manipulation.


I did a website some weeks ago with this feature. I created a function to know what section are the active and put it on the state in react. This function is called everytime the user move the scrollbar.

In render, I change de className of the elements depending the element of the state. In every section/element that i want to track I put an ID.

Util function:

/**
 * Helper function to get an element's exact position
 * @param  {element}  element
 * @return {x,y}
 */
export function getPosition(el) {
  var xPos = 0;
  var yPos = 0;

  while (el) {
    if (el.tagName == "BODY") {
      // deal with browser quirks with body/window/document and page scroll
      var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
      var yScroll = el.scrollTop || document.documentElement.scrollTop;

      xPos += (el.offsetLeft - xScroll + el.clientLeft);
      yPos += (el.offsetTop - yScroll + el.clientTop);
    } else {
      // for all other non-BODY elements
      xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
      yPos += (el.offsetTop - el.scrollTop + el.clientTop);
    }

    el = el.offsetParent;
  }
  return {
    x: xPos,
    y: yPos
  };
}

On React component:

componentDidMount() {
    window.addEventListener('scroll', this.handleScroll);
    this.handleScroll();
}

componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
}

handleScroll() {
    const {inAnimation} = this.state;

    let activeElement = false;

    this.props.data.items.forEach((value,i) => {
        let element = document.getElementById(value.url.substring(1));
        if(getPosition(element).y <= 0){
            activeElement = value.url;
        }
    });
    this.setState({
        activeElement
    });
    }
}
render(){
     ...
     items.map((item, i) => {
        return <li key={i}>
            <a className={'menu-item' + (activeElement == item.url ? ' active': '')}>{item.title}</a>
        </li>;
    });
     ...
}

Animations for your GatsbyJS site with Pose - Aaron, With full performance setup your pages should load straight away. In this example I'm going to use a basic template that GatsbyJS provides with the One example on the Pose documentation shows how we can zoom into an active: false }; nice example of Vince Parulan creating a lovely animated menu with Pose. Gatsby is an open source, modern website framework that builds performance into every site by leveraging the latest web technologies such as React and GraphQL. Create blazing fast apps and websites without needing to become a performance expert. Gatsby Cloud: The best way to create, update, and deploy Gatsby sites.


Link provides two options for adding styles to the active link:

activeStyle — a style object that will only be applied when the current item is active

activeClassName — a class name that will only be added to the Link when the current item is active

Follow official docs: https://www.gatsbyjs.org/docs/gatsby-link/#add-custom-styles-for-the-currently-active-link

import React from "react"
import { Link } from "gatsby"

const SiteNavigation = () => (
  <nav>
    <Link
      to="/"
      {/* This assumes the `active` class is defined in your CSS */}
      activeClassName="active"
    >
      Home
    </Link>
    <Link
      to="/about/"
      activeStyle={{ color: "red" }}
    >
      About
    </Link>
  </nav>
)

Add option to gatsby-link for matching active when on child routes , Basically I'd want to be able to designate a Link as active when any child any child routes are also active, without having to bypass gatbsy-link and use the current page) and if it is not, it sets className to item active . gatsbyjs deleted a comment from gatsbot bot on Feb 25, 2019 No one assigned. To do so, you’ll use a function passed to your API implementation called createNodeField. This function allows you to create additional fields on nodes created by other plugins. Only the original creator of a node can directly modify the node—all other plugins (including your gatsby-node.js) must use this function to create additional fields.


How to build a manageable menu/navigation with Kentico Kontent , You can use this content type to create one or multiple menus like your header and A navigation item is where the actual linking to a specific page/template OR an external URL happens. Build navigation components in GatsbyJS return ( <nav className="navigation"> <ul> {navItems.map((item,  Gatsby provides an easy way to use a local HTTPS server during development, thanks to devcert. When you enable the https option, a private key and certificate file will be created for your project and used by the development server. Usage (Automatic HTTPS) Start the development server using npm run develop as usual, and add either the -S or --https flag.


Customizing html.js is a workaround solution for when the use of the appropriate APIs is not available in gatsby-ssr.js. Consider using onRenderBody or onPreRenderHTML instead of the method above. As a further consideration, customizing html.js is not supported within a Gatsby Theme.


GraphQL is a query language (the QL part of its name). If you’re familiar with SQL, it works in a very similar way. Using a special syntax, you describe the data you want in your component and then that data is given to you. Gatsby uses GraphQL to enable components to declare the data they need.


(Explanation of Purify’s options, here.) As you can see, that implementation is quite fragile, requiring both specifically-defined file globs for the paths to scan and carefully selected whitelisted selectors (the webfonts-loaded and is-reverse classes are specific to my project, but everyone is likely to need at least markdown).