Coder Social home page Coder Social logo

brohlson / gatsby-plugin-anchor-links Goto Github PK

View Code? Open in Web Editor NEW
68.0 3.0 22.0 1.39 MB

⚓ Gatsby plugin for using smooth scroll anchor links with a Gatsby Link component

Home Page: https://www.npmjs.com/package/gatsby-plugin-anchor-links

License: MIT License

JavaScript 100.00%
gatsby gatsby-link gatsby-anchor-links gatsby-plugin

gatsby-plugin-anchor-links's People

Contributors

brohlson avatar pzmudzinski avatar tedsczelecki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

gatsby-plugin-anchor-links's Issues

Not working

I followed the instructions but I couldn't get it to work at all.

Scroll only works on second click

Hi!

I use this plugin on a FAQ page with on the top of the page a row of anchor links to different sections of the page. But when I click this anchor link, it jumps, without smooth scroll animation, it instantly jumps to the correct section. When I scroll back up and use the anchor link again, the scroll animation is working.

Is there something wrong with my component?

 <p className="tracking-widest text-mainPink-500">
                                    <AnchorLink
                                      to={`/veelgestelde-vragen/#${slice2.primary.title.text}`}
                                      title={slice2.primary.title.text}
                                    >
                                      {slice2.primary.title.text}
                                    </AnchorLink>
                                  </p>

delay while page content loads?

Thanks for building this.

I'm using the plugin on a site that is very image heavy.
I am linking from the homepage to anchors on interior pages.
On the first try, it seems to be hitting the anchor correctly but the anchor then moves as my images load.
On subsequent tries, it lands correctly and stays in place.
Is there anyway to be sure that content has loaded before landing on the anchor?

Add delay for compatability with page transition animations

  • Scrolling delay parameter.

Ideally, the scroller should delay until the page transition animations are finished.
In my case, I am trying to get this plugin to work with page transition fade animations (gatsby-plugin-transition-link). The issue is that I'm seeing is the scroller starts at the same time as the current page begins to fade out.

I was hoping that I could figure this out and then share the solution with you. But, I can't seem to get it!

Thank you for sharing this plugin. I really like it!

Comparison Shouldn't Fail When 'To' Contains a Query String / Search

The comparison between window.location.pathname will always fail if the the to contains a query string, for example if the to is: /example/?id=1234#foo, the comparison will be between pathname which is only /example/ and everything before the hash /example/?id=1234, which will fail.

Code here

if (window.location.pathname === withPrefix(anchorPath)) {

Different pages nav, bug offset scroll

When I click to navigate between pages with a hash, the offset is different and a page scrolls further than it should, has anyone experienced this problem?

AnchorLink can not be used with Material Ui

import { Link } from "@material-ui/core";
import { AnchorLink } from "gatsby-plugin-anchor-links";

<Link
  component={AnchorLink}
  to="/about"
  variant="h6"
  color="primary"
  gutterBottom
  stripHash  >
 about
</Link>

This code produces the following browser errors:

Warning: Failed prop type: Invalid prop component supplied to ForwardRef(Link). Expected an element type that can hold a ref. Did you accidentally provide a plain function component instead? For more information see https://material-ui.com/r/caveat-with-refs-guide

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

--

I use Material Ui. Passing GatsbyLink to Material UI Links works fine. But AnchorLinks can not be passed to the component prop. The MUi Docs say that AnchorLinks must be able to hold a Ref for this to work.

Hashtag doesn't change on current page

Hello,

so I got these two files with the AnchorLink setup properly.

index.js

import * as React from "react"
import { Link } from "gatsby"
import { StaticImage } from "gatsby-plugin-image"

import Layout from "../components/layout"
import SEO from "../components/seo"
import { AnchorLink } from "gatsby-plugin-anchor-links"

const IndexPage = () => (
  <Layout>
    <SEO title="Home" />

    <AnchorLink to="/#test">got to #test</AnchorLink>
    <div style={{ marginTop: 800 }}></div>
    <div id="test">test</div>

    <Link to="/page-2/">Go to page 2</Link>
    <Link to="/using-typescript/">Go to "Using TypeScript"</Link>
  </Layout>
)

export default IndexPage

page-2.js

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

import Layout from "../components/layout"
import SEO from "../components/seo"

const SecondPage = () => (
  <Layout>
    <SEO title="Page two" />
    <Link to="/#test">Go back to #test</Link>
  </Layout>
)

export default SecondPage

Now if I'm on my Index page, I want that if i click on <AnchorLink to="/#test">got to #test</AnchorLink> that the hashtag gets added to the URL. The default behavior is, that it just scrolls to to #test, but doesn't add the hashtag to the link.
How can I archive that?

add option to provide custom onClick

It's not possible right now to set a custom onClick event handler on the AnchorLink component, hence become difficult to make changes related to components (such as setting state variables). Would be nice to add such kinda functionality.

Anchor Link with gatsby intl

Hello i am wondering how to manage Hash with gatsby Intl plugin. Any idea all my test failed.
import {Link} from 'gatsby-plugin-intl' with gatsby anchor failed and redirect to the top of the pages.

Best regards

No smooth scroll for anchor, only for offset

I'm not getting a smooth scroll to the anchor, it jumps to the anchor and does a smooth scroll to the offset.
Before I was using react-anchor-link-smooth-scroll where the smooth scroll is working.

Am I missing something?

import { AnchorLink } from 'gatsby-plugin-anchor-links'
import React from 'react'
import PropTypes from 'prop-types'
import { IntlContextConsumer } from 'gatsby-plugin-intl'

const AnchorLinkIntl = ({ to, language, children, ...rest }) => (
<IntlContextConsumer>
	{intl => {
		const languageLink = language || intl.language
		const link = intl.routed || language ? `/${languageLink}${to}` : `${to}`

		return (
			<AnchorLink {...rest} to={link}>
				{children}
			</AnchorLink>
		)
	}}
</IntlContextConsumer>
)

AnchorLinkIntl.propTypes = {
	children: PropTypes.node.isRequired,
	to: PropTypes.string,
	language: PropTypes.string
}

AnchorLinkIntl.defaultProps = {
	to: ''
}

export default AnchorLinkIntl

Different section offset when going from another page

I have a navigation problem when navigating to a section from a non-home page where that section is located.

CodeAnchor

This view of section when i click nav item on homepage
ContactAnchor

And this is when i click nav item from another page
ContactAnchorOther

Feature Request: Per-link offset

It would be great to be able to specify an offset for specific links to override the global offset. This could be provided in the form of a query string that is parsed out by the plugin when introspecting for the hash:

https://example.com/?offset=30#some-component-id

Hash params crashing application

I'm attempting to integrate a Gatsby app with an external authentication tool that uses OIDC. As is typical, I link over to the external provider's login page, enter credentials, log in, then that page authenticates the user, and sends them back via the redirect URI, which contains a bunch of hash parameters, token_type, id_token, etc.

Because they're coming in as hash parameters (https://domain.com/page/#token_type=Bearer&id_token=eyJ...Y1st5OQ), and not query parameters (https://domain.com/page/?token_type=Bearer&id_token=eyJ...Y1st5OQ), there is a conflict with this plugin.

It seems to want to check the DOM for an element with an ID given by the hash string appended to the redirect URL. The error

Document.querySelector: '#token_type=Bearer&id_token=eyJ...Y1st5OQ' is not a valid selector.

is thrown, and the application crashes.

Could this plugin safely navigate this error?

Id:s that start with a number aren't navigable

Description

When an id starts with a number, like an element with id="1-Sign-Up-to-create-the-User", it crashes when trying to be scrolled to.

Steps to reproduce

Apply gatsby-plugin-anchor-links on a Gatsby website with an anchor link.

In my setup I use gatsby-plugin-mdx with gatsby-remark-autolink-headers to generate the id:s and links, but I'm positive any page with an id value that starts with a number will suffice.

Expected result

The id should be scrolled to successfully.

Actual result

It crashes on:

Uncaught DOMException: Document.querySelector: '1-Sign-Up-to-create-the-User' is not a valid selector

because of the dependency of this package, https://github.com/willhoag/scroll-to-element.

Environment

System:
    OS: macOS 10.15.7
    CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    Shell: 4.4.23 - /nix/store/idf48ng7jlz9jrmv0c2bkj0i3xxbdhrp-bash-interactive-4.4-p23/bin/bash
  Binaries:
    Node: 12.18.4 - /nix/store/lcr10m9cfdm1qpd0kzjgb2iy8mmxcjjc-nodejs-12.18.4/bin/node
    Yarn: 1.22.5 - /nix/store/0dbynkravj7lixj5mg19vmaxgdxsp5wm-yarn-1.22.5/bin/yarn
    npm: 6.14.6 - /nix/store/lcr10m9cfdm1qpd0kzjgb2iy8mmxcjjc-nodejs-12.18.4/bin/npm
  Languages:
    Python: 2.7.16 - /usr/bin/python
  Browsers:
    Chrome: 88.0.4324.150
    Safari: 14.0.3
  npmPackages:
    gatsby: ^2.29.0 => 2.29.1
    gatsby-background-image: ^1.1.2 => 1.1.2
    gatsby-image: ^2.2.34 => 2.4.6
    gatsby-plugin-anchor-links: ^1.1.1 => 1.1.1
    gatsby-plugin-google-analytics: ^2.3.13 => 2.3.13
    gatsby-plugin-local-search: ^1.1.1 => 1.1.1
    gatsby-plugin-manifest: ^2.2.31 => 2.4.10
    gatsby-plugin-mdx: ^1.2.5 => 1.2.14
    gatsby-plugin-offline: ^3.0.27 => 3.2.8
    gatsby-plugin-postcss: ^2.3.1 => 2.3.3
    gatsby-plugin-react-helmet: ^3.1.16 => 3.3.3
    gatsby-plugin-sass: ^2.3.14 => 2.3.14
    gatsby-plugin-sharp: ^2.3.5 => 2.6.10
    gatsby-plugin-sitemap: ^2.4.12 => 2.4.12
    gatsby-remark-autolink-headers: ^2.3.2 => 2.3.4
    gatsby-remark-embed-markdown: https://github.com/dhakan-k/gatsby-remark-embed-markdown => 0.0.4
    gatsby-source-filesystem: ^2.1.40 => 2.3.10
    gatsby-source-git: ^1.1.0 => 1.1.0
    gatsby-transformer-sharp: ^2.3.7 => 2.5.4
    gatsby-transformer-yaml: ^2.4.0 => 2.4.3

Change URL when clicking on an AnchorLink

Hello,

First of all, thanks for creating/sharing this plugin!

It works perfectly for my needs, but there's one issue I have with it. When I am on Page /X and click on an AnchorLink pointing to /X#some-anchor, then it does scroll to the anchor, but the URL doesn't change.

Would it be possible to add this behavior as an option, or to pass the target of the AnchorLink to the onAnchorLinkClick function?

I'm using this here: https://www.dev-concepts.dev/table-of-contents, for the overview on the right; clicking on one of the boxes brings the reader to one of the anchors.

className and activeClassName props

This Gatsby plugin is really nice however, classes, id's, active classes, etc cannot be defined or attached like a Gatsby Link or href. This results in awesome functionality that needs workarounds to style properly. Maybe I'm missing something?

Also if you are having issues getting the plugin to work on other pages try adding the offset in the config. This immediately made this feature work for me. Without the offset in the config, it would not work on my other pages.

Scroll to location when using direct URL

Thanks for this plugin! Scrolling to destinations within a page work great. Users can land on some page, example.com/page, and then clicking an anchor link, say #some-location, scrolls the user to that location, as expected.

However, a request has come my way for implementing that same functionality when someone visits the URL example.com/page#some-location directly. That is, scroll to the desired location once the page has rendered.

Is this already possible, or is that functionality you've considered implementing for this plugin? Not sure how it would work in this case--perhaps a delay, but I'm not sure.

Adding slashes to links results in delay on clicking

Hey! I changed the formatting of my hashed paths from #watch to /#watch to avoid the error External link #watch was detected in a Link component. Use the Link component only for internal links. See: https://gatsby.dev/internal-links., however now I get a small yet frustrating delay when the links are clicked - any idea why this could be happening? Thanks!

Add note to README regarding trailingSlash

Just started a new Gatsby project, looks like by default the trailingSlash property in the gatsby-config.js is set to "always" by default. This affects the ability to smooth scroll and ran into this just now and figured some other peeps might also run into this.

Might be worth adding to the docs?

Scroll Animation Speed Changes

Hi, not sure why but the scroll animation speed starts off slow and changes to a faster one. Here are the packages I am using.

        "@react-icons/all-files": "^4.1.0",
        "babel-plugin-styled-components": "^1.12.0",
        "gatsby": "^3.0.1",
        "gatsby-plugin-anchor-links": "^1.2.1",
        "gatsby-plugin-image": "^1.0.0",
        "gatsby-plugin-layout": "^2.0.0",
        "gatsby-plugin-manifest": "^3.0.0",
        "gatsby-plugin-netlify-cms": "^5.0.0",
        "gatsby-plugin-react-helmet": "^4.0.0",
        "gatsby-plugin-sharp": "^3.0.0",
        "gatsby-plugin-sitemap": "^3.0.0",
        "gatsby-plugin-styled-components": "^4.0.0",
        "gatsby-source-filesystem": "^3.0.0",
        "gatsby-transformer-sharp": "^3.0.0",
        "netlify-cms-app": "^2.14.26",
        "react": "^17.0.1",
        "react-dom": "^17.0.1",
        "react-helmet": "^6.1.0",
        "styled-components": "^5.2.1"

Only seems to work as intended when already on same page as hash/id

Thanks for your work on this, and it's a great idea (if I'm understanding the intention of the project correctly). Unfortunately, I'm only getting the scroll behavior upon clicking the anchorlink when I'm already on the same page as the destination hash/id.

This plugin is intended to work across different pages as well, right? I've been using this plugin for same-page smooth-scrolling just fine, but have been struggling with getting similar behavior across pages.

When I have more time I'll look into whether gatsby-plugin-layout, which I also have enabled for transition purposes, is messing with any of this (because I also tried something by hand to achieve the effect I'm looking for, which also didn't work as expected).

using stripHash doesnt work on production

i tried to use the plugin like this in gatsby-config.js

        {
            resolve: 'gatsby-plugin-anchor-links',
            options: {
                offset: -100,
            },
        },

and

 <AnchorLink to="/#how-it-works" stripHash>How it works</AnchorLink>
 <AnchorLink to="/#about-us" stripHash>About us</AnchorLink>
 <AnchorLink to="/#our-clients" stripHash>Testimonials</AnchorLink>

when run in local it works, smooth scroll also works, but when i deploy to netlify, eveytime i click on the link, it just goes to the top page, if i dont use stripHash, it will just go to the target, no smooth scroll.

Expose Link API

  • Pass user generated gatsby-link props through to the wrapped component noted in #6

Anchor the element in the same page not working.

Hi there.

I would like to use the table of content to anchor the elements in the mdx, which in the same page, but it doesn't work.

I use the gatsby file system to generate pages by the mdx files.

This is the Layout of the mdx template to add the AnchorLink to the h1 tags.

import React from "react";
import { MDXProvider } from "@mdx-js/react";
import { AnchorLink } from "gatsby-plugin-anchor-links";

const MyH1 = (props) => {
  return (
    <h1>
      <AnchorLink to={"#" + props.children}>{props.children}</AnchorLink>
      {/* <a href={"#" + props.children}>{props.children}</a> */}
    </h1>
  );
};

const components = {
  h1: MyH1,
};

export default function Layout({ children }) {
  return <MDXProvider components={components}>{children}</MDXProvider>;
}

And this is a part of my code to generate table of content :

 export const MyToc = ({ url, title, items, level = 0 }) => {
  const hasChildren = items && items.length;

  return (
    <div>
      <AnchorLink to={url} style={{ paddingLeft: level * 20 + "px" }}>
        {title}
      </AnchorLink>

      {hasChildren &&
        items.map((item) => (
          <MyToc key={item.title + item.url} {...item} level={level + 1} />
        ))}
    </div>
  );
};

However, it cannot jump to the element which is in the same page. If I click the anchor element, the URL in the browser will like this: http://localhost:8000/contents/alexnet/#Alexnet. It is the page URL: http://localhost:8000/contents/alexnet/. The hash tag cannot attach behind the page without /.

Thank you for your loveable work.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.