gabergg / react-scrollable-anchor Goto Github PK
View Code? Open in Web Editor NEWSmooth scrolling anchors bound to URL hash
License: MIT License
Smooth scrolling anchors bound to URL hash
License: MIT License
In some projects I need anchor links with scrolling but without automatic URL hash updates. I think it would be useful to make the URL hash updates optional
I think ScrollableAnchor can be modified to be a self-contained component like so:
<ScrollableAnchor id="some_id" />
The children should be optional.
Getting error using implementation as explained
error output:
invariant.js:44 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of `ScrollableAnchor`.
at invariant (invariant.js:44)
at ReactCompositeComponentWrapper.instantiateReactComponent [as _instantiateReactComponent] (instantiateReactComponent.js:68)
at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:367)
at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
at Object.mountComponent (ReactReconciler.js:46)
at ReactDOMComponent.mountChildren (ReactMultiChild.js:238)
at ReactDOMComponent._createInitialChildren (ReactDOMComponent.js:691)
at ReactDOMComponent.mountComponent (ReactDOMComponent.js:516)
at Object.mountComponent (ReactReconciler.js:46)
at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:371)
React version: 15.4.1
It would be good for menu item highlighting if it was possible to get the anchor ID of the currently visible anchor in the view.
This works great for jumping to different sections by menu but I have been experiencing an issue when scrolling manually. I see a forced jump to a section when a small part of a section is within view. Is there any way to turn that off? It almost reminiscent of the forced scrolling you sometimes see which leaves the user feeling out of control. See example here: https://tinyurl.com/y7rswsoy
Hi. I have 15 React and 3 React Router. Do you supported it?
"react": "^15.4.2",
"react-router": "^3.0.2",
I have this markup:
<ul className="links">
<li>
<a href="#link1">
Link 1
</a>
</li>
<li>
<a href="#link2">
Link 2
</a>
</li>
<li>
<a href="#link3">
Link 3
</a>
</li>
<li>
<a href="#link4">
Link 4
</a>
</li>
<li>
<a href="#link5">
Link 5
</a>
</li>
</ul>
<ScrollableAnchor id={"link1"}>
<div>
.......
</div>
</ScrollableAnchor>
So it's not working. No errors in console. Url hash is changing, but viewport not scrolled
Here the response and the cli command
❯ yarn add react-scrollable-anchor
yarn add v1.3.2
[1/4] 🔍 Resolving packages...
[2/4] 🚚 Fetching packages...
error https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz: Fetch succeeded for undefined. However, extracting "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz" resulted in hash "47e63f7af55afa6f92e1500e690eb8b8529c099a", which did not match the requested hash "47e63f7af55afa6f92eloadingOute690eb8b8529c099a".
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.
This could be solved by #19. As a workaround, I'm doing the following:
<ScrollableAnchor id="test">
<div>
<MyStatelessComponent/>
</div>
</ScrollableAnchor>
The error is as follows:
Warning: Stateless function components cannot be given refs. Attempts to access this ref will fail.
Check the render method ofScrollableAnchor
.
Then, it also throws what's described in #43. Using the div hack solves the matter.
Hello, the library works good, I just was wondering if its possible to smoothly scroll to the section when you using the back and forward buttons. Thank you.
I am new to React so this may just be missing something with syntax, but I can't seem to get dynamic content into this tag.
I've tried:
<ScrollableAnchor id={'section1'}>
item.map((course, index) => (
<div><span>{course.prog.label} {course.prog.title}</span> </div>
)),
</ScrollableAnchor>
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `ScrollableAnchor`.
and several versions thereof. I've tried passing in variables. I've tried loading other tags. There doesn't seem to be any way to pass it dynamic content. Is this possible and I'm missing something? OR is this not designed with dynamic content in mind.
Thank you
when using with a simple function component as follow:
<ScrollableAnchor id={"faq"} >
<BlockTitle>
FAQ
</BlockTitle>
</ScrollableAnchor>
const BlockTitle = ({ children, ...props }) => {
const classes = useStyles()
return (
<Typography className={classes.title} variant="h2" {...props}>
{children}
</Typography>
)
}
React doesn't like it and report the following warning:
Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
If I use a plain <div>
rather than a custom component it work though.
This is maybe linked to the clone element from the ScollableAnchor.
It looks like it doesn’t work with styled-components. I used it as in the documentation but styled-components changed your scroll component to a div with class. It doesn’t have an id for the anchor anymore.
Hello, so I'm trying to use the simplest possible example but it won't work.
My link looks like this:
<a href="#step4">SGo to section 4</a>
My component looks like this:
< ScrollableAnchor id={"step4"}> <div>Ipsum Lorem Ipsum</div> </ScrollableAnchor>
So this triggers the jump to the div id but no animation happens at all even if I for example set the scrollDuration to 1000.
My component is a modal so might this cause some issues?
Thanks!
What I do:
I am using <base href="/">
in the <head>
of the html file and scrolling through the sections.
What I see:
it won't update the hash relative to the path but will use the base path to append the hash to.
This then goes to a complete new site because the router reacts to the route change.
What I expect:
The route should stay the same, but only the hash should change.
Possible solution:
In https://github.com/gabergg/react-scrollable-anchor/blob/master/src/utils/hash.js it should also use the rest of the path to build the complete URL instead of just updating the URL.
Hello!
I had sucess using this with ReactJs. When I changed my components to stateless, it stoped working. Can I make this work in some way?
Tried to use it with react-bootstrap's navigation bar, doesn't seem to work.
What Is It? How To Get Started?It suddendly stopped working dont know why.
Even the sample code doesnt work
<div>
<a href='#section1'> Go to section 1 </a>
<a href='#section2'> Go to section 2 </a>
<ScrollableAnchor id={'section1'}>
<div> Hello World </div>
</ScrollableAnchor>
<ScrollableAnchor id={'section2'}>
<div> How are you world? </div>
</ScrollableAnchor>
</div>
but the demos here still work?? http://gabegsell.com/anchors/
It works well on Firefox, chrome, IE10, IE11, Edge, except IE9, anyone has any ideas for this? Thanks in advance.
hello
no matter what i put in configureAnchors, it doesn't change anything.
for example adding this has no effect :
import {goToAnchor, configureAnchors} from "react-scrollable-anchor";
configureAnchors({offset: -260, scrollDuration: 1200});
this too :
import {goToAnchor, configureAnchors} from "react-scrollable-anchor";
configureAnchors({offset: 60, scrollDuration: 200});
but the goToAnchor
work
onClick={() => {
goToAnchor("graph");
}}
any idea ? thanks
TypeError: _react.PropTypes is undefined
Here where it's breaking:
ScrollableAnchor.propTypes = {
children: _react.PropTypes.node,
id: _react.PropTypes.string
};
exports.default = ScrollableAnchor;
Hello, first, thanks for the library.
I'm trying to use it on my website but when I use a Link
component (from react-router-dom) to redirect to a ScrollableAnchor
, it's not working at all even if I use the goToAnchor on the onClick attribute. While it's working great with a <a>
tag.
Here is my code (The only working one is Test3
):
export default class MainNav extends Component {
scrollToAnchor = (anchor) => {
goToAnchor(anchor, true)
}
render() {
return (
<div>
<Nav>
<Container lg>
<NavContent>
<LogoContainer>
<Link to={routes.home}>
<MainLogo width="25px" height="25px" />
</Link>
</LogoContainer>
<LinksContainer>
<Link to="/#contactBlock">Test1</Link>
<Link onClick={this.scrollToAnchor('#contactBlock')}>Test2</NavLink>
<a href="/#contactBlock">Test3</a>
</LinksContainer>
</NavContent>
</Container>
</Nav>
</div>
)
}
}
And here is the code that contain the ScrollableAnchor
component:
export default class Home extends Component {
render() {
return (
<div>
<MainHeader />
<Container>
<ScrollableAnchor id="aboutBlock">
<About />
</ScrollableAnchor>
<ScrollableAnchor id="projectsBlock">
<Projects />
</ScrollableAnchor>
</Container>
<ScrollableAnchor id="contactBlock">
<Contact />
</ScrollableAnchor>
<EasterEgg />
<MainFooter />
<SplashScreen />
</div>
)
}
}
Any idea? Am I doing something wrong?
Hi there!
i've tried to use it on two different components, a menu and the other components (which contains the anchors) When i click on the menu nothing happens however the URL is correctly modified. if I let it as localhost/#item and refresh the browser it correctly scrolls down to the element.
Any idea how I can fix this?
Lib doesn't work if I go through encoded link with unicode symbols in anchor. It could be simple fixed by adding encodeUri in getHash method.
import { removeHash } from 'react-scrollable-anchor'
// clear URL hash
removeHash()
I tried placing this inside parent component, child component, App.js. Its not working. Where should this be placed? How to use this?
Hello!
My project React version: 15.6.2
Some time i have mistake:
Invalid prop id of type number supplied to ScrollableAnchor, expected string.
What can i do with this?
Hello,
So i'm trying to use Scrollable Anchor on a link in the navbar to scroll down to an anchor on the homepage. It's working perfectly when i'm on the homepage but if i'm on another page it redirects me to the homepage but doesn't scroll down enough, it stops halfway.
Can you help me please ?
I've tried to use the goToAnchor method but i'ts not working either
Thanks !
Hi, I have an odd issue. When I use the button it works perfectly, but some people may still try to use the scroll down with the mouse, so I try it and when I do it with the mouse it takes me to the top again.
I've seen in the address bar I have https://localhost:3000 and when I'm scrolling down I have https://localhost:300/#section04 but the hashtag disappear automatically and therefore the page scrolls up automatically.
What can I do?
I have a page where content is rendered after a remote file is retrieved on componentDidMount.
This causes the anchor links to scroll to a different position than expected. All links above the dynamic content work fine.
I got this error while compiling:
Module build failed: Error: Couldn't find preset "es2015-rollup" relative to directory "/Users/piaaaac/code/dd-mag/node_modules/jump.js"
Adding babel-preset-es2015-rollup
led to successful compiling but now I'm getting:
Uncaught ReferenceError: babelHelpers is not defined
at jump.min.js:7
at Object.defineProperty.value (jump.min.js:7)
at __webpack_require__ (bootstrap 910dd27f6e55ce09ccba:54)
at Object.defineProperty.value (Manager.js:9)
at __webpack_require__ (bootstrap 910dd27f6e55ce09ccba:54)
at Object.<anonymous> (ScrollableAnchor.js:21)
at __webpack_require__ (bootstrap 910dd27f6e55ce09ccba:54)
at Object.defineProperty.value (index.js:23)
at __webpack_require__ (bootstrap 910dd27f6e55ce09ccba:54)
at Object.<anonymous> (helpers.js:78)
Could anyone help me out? thx
I have "react": "^15.5.4", "react-scrollable-anchor": "^0.4.2".
This can apparently be solved by adding ,
offset: _this.config.offset + 10, in Manager.js.
Configuring the offset as shown in the docs doesn't resolve the issue.
Hey Gabe - thanks so much for this scroller! I wanted to let you know I had an error on install of the react-scrollable-anchor when I tried to import to the component.
Failed to compile.
Error in ./~/react-scrollable-anchor/~/react-dom/index.js
Module not found: 'react/lib/ReactDOM' in /Users/Heidi/Desktop/hp-portfolio/node_modules/react-scrollable-anchor/node_modules/react-dom
@ ./~/react-scrollable-anchor/~/react-dom/index.js 3:17-46
I changed
module.exports = require('react/lib/ReactDOM');
to
module.exports = require('react-dom/lib/ReactDOM');
and it started up without a problem. I used the react-create-app
command for this project if that makes a difference. Thanks again!
URL Example: "https://github.com//gabergg/react-scrollable-anchor/issues/29".
There is a double slash on the "https://github.com//". Using the lib, we got an error:
Uncaught DOMException: Failed to execute 'replaceState' on 'History'
Should this be handled by the package?
The hash gets only updated when you're not scrolling or swiping - even if you're already at another anchored section.
I expect the update of the anchor as soon as the new section appears in the viewport.
I need to do things based on which section I am currently on. Can I get the hash without displaying it in the url?
What I do:
I am using a custom history (but still using the browser history) in react-router
and scroll through sections.
What I see:
It re-mounts the route component because react-router handles this as a complete route change causing jumping to the top of the page.
What I expect:
The hash should change, but the route should not be re-rendered.
Possible solution:
passing a custom hash update function to the ScrollableAnchor
component that will handle the hash change in a custom matter (using the history
prop that react-router
provides).
Hi, the plugin is not working when you have a parameter and a hash value in URL example:
http://www.example.com?referrer=facebook#element_id
Can we use any option, or does anybody have a solution for that ?
It would be useful to allow other containers to scroll, for where the main view is static, but it is an internal div that scrolls.
My entire app is this:
import React from 'react'
import ReactDOM from 'react-dom'
import Photo from '../components/photo'
import {createClient} from 'contentful'
import ScrollableAnchor from 'react-scrollable-anchor'
// import { configureAnchors } from 'react-scrollable-anchor'
// Offset all anchors by -60 to account for a fixed header
// and scroll more quickly than the default 400ms
// configureAnchors({offset: -60, scrollDuration: 200, keepLastAnchorHash: true})
const client = createClient({
space: '[redacted]',
accessToken: '[redacted]'
})
const App = ({assets}) => {
return (
<div className="list">
{
assets.map(asset =>
<ScrollableAnchor id={asset.fields.id}>
<div style={{height: '1000px'}}>test</div>
{/* <Photo photo={asset} /> */}
</ScrollableAnchor>
)
}
</div>
);
};
document.addEventListener('DOMContentLoaded', () => {
client.getAssets()
.then((response) => ReactDOM.render(<App assets={response.items}/>, document.getElementById('app')))
.catch(console.error)
})
I get this error after a scroll stops:
Uncaught TypeError: Cannot read property 'getBoundingClientRect' of null
at getElementOffset (scroll.js:14)
at doesElementContainScrollTop (scroll.js:29)
at scroll.js:88
at Array.forEach (<anonymous>)
at getBestAnchorGivenScrollLocation (scroll.js:86)
at Manager.handleScroll (Manager.js:76)
at later (func.js:15)
getElementOffset @ scroll.js:14
doesElementContainScrollTop @ scroll.js:29
(anonymous) @ scroll.js:88
getBestAnchorGivenScrollLocation @ scroll.js:86
Manager.handleScroll @ Manager.js:76
later @ func.js:15
setTimeout (async)
(anonymous) @ func.js:20
(context: I just want something that changes the URL of the page to have a fragment corresponding with whatever picture is currently in the viewport, so that if the link is shared, the browser will scroll to that specific picture. Shouldn't be hard, right?)
This is slightly related to #8 in that this is an accessibility issue. Activating a link should not just scroll to the target, it should set the focus there also. This is what happens when <a>
is used on an HTML page. Since the package is a replacement for anchors, it should emulate their accessibility functionality as well.
I found some of the features in this library nice and wonder how can it be expanded or if this connects well with other libraries.
My use case is this:
A nav header, on top, quite big;
When the user scrolls down, the said nav header shrinks and is kept sticky.
From my current reasoning I would say:
goToTop() function goes to top not smoothly. It jumps like regular HTML anchor
Hey guys,
whenever installing react-scrollable-anchor from npm directory I never get the fixed version with PropTypes package
Thanks for the awesome lib.
I want to have different offsets for different links. Currently setting configureAnchors({ offset: -30 });
changes offset for all links.
I'm using semantic-ui-react
in lieu of Bootstrap and needed to reinstall this package after installing react-scrollable-anchor
. The error message said it couldn't locate semantic-ui-css/semantic.min.css
within index.js
. Semantic is once again running perfectly after the reinstall.
Anyone else experienced the same?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.