Git Product home page Git Product logo

react-scrollspy's Introduction

DEPRECATED - no longer actively maintained.

Please use GhostUI instead.

react-scrollspy

npm version travis dependencies DevDependencies License downloads

Scrollspy component

Demo

Install

$ npm i react-scrollspy

Usage

import Scrollspy from 'react-scrollspy'

...

<div>

  <div>
    <section id="section-1">section 1</section>
    <section id="section-2">section 2</section>
    <section id="section-3">section 3</section>
  </div>

  <Scrollspy items={ ['section-1', 'section-2', 'section-3'] } currentClassName="is-current">
    <li><a href="#section-1">section 1</a></li>
    <li><a href="#section-2">section 2</a></li>
    <li><a href="#section-3">section 3</a></li>
  </Scrollspy>

</div>

Props

items={ Array }

Id list of target contents.

currentClassName={ String }

Class name that apply to the navigation element paired with the content element in viewport.

scrolledPastClassName={ String }

Class name that apply to the navigation elements that have been scrolled past [optional].

componentTag={ String | React element type }

HTML tag or React Component type for Scrollspy component if you want to use something other than ul [optional].

style={ Object }

Style attribute to be passed to the generated <ul/> element [optional].

offset={ Number }

Offset value that adjusts to determine the elements are in the viewport [optional].

rootEl={ String }

Name of the element of scrollable container that can be used with querySelector [optional].

onUpdate={ Function }

Function to be executed when the active item has been updated [optional].

Methods

offEvent

Remove event listener of scrollspy.

onEvent

Add event listener of scrollspy.

Development

$ git clone https://github.com/makotot/react-scrollspy.git
$ cd react-scrollspy
$ npm i
$ npm run start

Contributing

Pull requests and reporting an issue are always welcome :)

License

MIT

react-scrollspy's People

Contributors

apena415 avatar caesay avatar davidjb avatar dunglas avatar feychenie avatar hsingh23 avatar jonespen avatar julianfresco avatar makotot avatar maxkferg avatar neemzy avatar tikotzky avatar trevtrich avatar yangshun 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-scrollspy's Issues

Could use some build instructions

I've got some ideas I'd like to contribute, but I can't figure out how to set up the project to run on its own. Tried with the typical npm install and npm start but ran into some problems (gulp was missing, installed it as global, got more errors)

Why does the titles in the nav bar don't get highlighted ?

I have one issue and one question :

Issue:
The titles in my nav bar are not being highlighted once I scroll to a specific "Section"

Question:
When I tap on a specific nav bar title, the scrollspy works fine and goes to the clicked section, but my question is :

  • instead of jumping right away to the clicked section, can it instead scroll down and not jump directly to the selected html section ?

clicking links doesn't highlight them

I think the lib should highlight the elements based on the hash and only if not present, on the scroll position.

right now I have a few navigation items on the same page and if i click those rather at the end, the page scrolls correctly but the highlight is set to the last item in my navigation.

This is probably due to the fact that the last item is also on the page.

Scrollspy can not be used in a scrollable container

Currently scrollspy watches for scroll events on the documentElement. This makes it so that ScrollSpy can not be used in a scrollable container. Attached is a sample use case to demonstrate the need for this feature.

image

#47 is currently out for review in attempt to support this use case. Looking forward to your thoughts!

nested

does not work collectly if nested.

Even the example doesn't work for me

Is there any requirements not documented? I'm using react ^16.8.6 and the navigation item won't be highlighted according to section. Also when I need to click the navigation item twice in order to make it highlighted.

How to get the element that was clicked on

Function onUpdate() return element which was scrolled.
Is there a possibility get element that was clicked ?

After all, currentСlass is-current is added to element.
Please help.

Supress console warning messages for componentWillMount and componentWillReceiveProps

I'm getting console warnings for both componentWillMount and componentDidMount after upgrading my React version to 16.9.0.

This can be easily fixed by changing those to UNSAFE_componentWillMount and UNSAFE_componentWillReceiveProps in scrollspy.js.

Should I make a PR? Or is someone already working on an update?

Update: After tinkering around on my own, that won't quite fix the problem. It then throws this warning intermittently:
Warning: Can't perform a React state update on an unmounted component. ...

I'll take another look ASAP to see if I can figure out a proper fix, unless someone is already working on this.

Second-to-last section never shows active

The active section always jumps from the third-to-last to the last section, never showing the second-to-last one as active.

My second-to-last section is full page height, so it's not an issue of both being on screen at the same time.

React version

Hi,

I tried to use this lib on a project powered by React v0.14.6 and it didn't work, as my version seemed to conflict with the one that is used internally (given your version constraint is ^0.13.3).

I'd suggest:

  • raising your version constraint; I can confirm your lib works up to v0.14.6 as I said
  • setting React as a peerDependency to avoid having it installed in your lib's own node_modules folder, and use the project's instead - having multiple versions of React coexisting is never a good idea in my experience.

Thanks for the lib anyway, it works great now :)

Cheers,

Demo is broken

Hey, demo site is broken. It seems to static assets have been lost, because app.min.js responded 404.

Sections larger than the screen result in no active HREF

Hi!

Say you have large section chunks which are larger than the viewport. If you are scrolling down the page, you'll end up in a situation where no <li> is highlighted, as no anchor is actually on the page. Should not the most recent highlight remain 'lit' until the next one appears?

Unexpected token <

I get this error when trying to load this module

Module parse failed: /Users/***/Sites/***/node_modules/react-scrollspy/src/js/lib/scrollspy.jsx Line 110: Unexpected token <

cannot npm install

ERROR: [Errno 2] No such file or directory: 'run' npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! [email protected] prepublish: yarn run build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] prepublish script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /home/nineleaps/.npm/_logs/2018-06-07T06_40_02_795Z-debug.log

npm ERR! missing script: start

npm ERR! A complete log of this run can be found in:
npm ERR! /home/nineleaps/.npm/_logs/2018-06-07T06_41_17_276Z-debug.log

`

smooth scroll

is the ways to scroll to section with transition or animation ???

_isInView is true so long as any of the item is on the page - leads to surprising behaviour

My webapp is made up of consecutive sections:
<section id="1">...</section>
<section id="2">...</section>
<section id="3">...</section>

From it's definition _isInView (see line 83) returns true for an element so long as the element's top is above the bottom of the window and its top is below the top.

Because of how getElemsViewState goes through the components one by one until it finds one in view (e.g. see line 50), so long as a component is on the screen at all then the next component will not be highlighted. (Alternately, if scrolling in the opposite order to the way the item keys are defined, the next component will be highlighted as soon as any of it is on screen).

This behaviour is especially strange in my webapp: When clicking on a link to a section, the previous section's navbar item is highlighted. It is made worse because I have a 75px fixed-top navbar as well.

As solutions to this I suggest finding the scrollspy item that occupies the middle of the page and specifying that this element is in view instead. E.g. changing:

`return (elTop < scrollBottom) && (elBottom > scrollTop)`

To:

`var midpoint = scrollBottom + (scrollTop - scrollBottom) / 2;
 return (elTop < midpoint) && (elBottom > midpoint);`

I've made this change locally and prefer it. I'd be happy to submit a pull request as well, but because it is a behavioural change it is better to open this issue first for discussion. E.g. it might be better to make this new behaviour optional via a property.

ability to provide a callback function when given li becomes active?

Is it possible to provide a callback function so that when a given li becomes active ('is-selected') we can do additional processing on it? something like:

        <Scrollspy
          items={['section-1', 'section-2', 'section-3']}
          currentClassName="is-current"
          onChange={(id) => console.log('the active li id is now', id)}
>
          <li><a href="#section-1">section 1</a></li>
          <li><a href="#section-2">section 2</a></li>
          <li><a href="#section-3">section 3</a></li>
        </Scrollspy>

A few recommendations

Cool library! I have a few recommendations that might make it less opinionated and a wee bit more customizable:

  • I suggest removing the wrapping nav element. It's not possible to opt out of it, and it's not really adding anything, right? Consumers can easily add that in on their own if they need to. I have a preference specify the nav markup outside of this lib.
  • Adopting a similar API as ReactTransitionGroup could be useful. It renders as a span unless the person specifies a component prop. This way, folks can use li, ul, div, or whatever they want.
  • accept a className prop to add a custom class name to the list component

I can make a PR if you think any of these are good ideas!

Module not found : scrollspy.js

hi,

when i install the latest build version which is 3.3.4, i am getting below error

Module build failed: Error: ENOENT: no such file or directory, open '/Users/sahusoft/Sites/projects/merge_wos_with_jaipur_team/wos-client/node_modules/react-scrollspy/scrollspy.js'

when i checked the lib folder it has Scrollspy.js instead of scrollspy.js.

Release commits don't include built files

Excluding built files from the repo is fine, but it's a good idea to force add them to the release commit. Some projects make a branch for the release, force add, then commit. The branch can then be deleted since git is immutable, and the commit sticks around f'eva.

The benefit of doing this is that folks can use the releases to consume the package. Atm the releases aren't consumable since they don't include any files at all.

Example after installing through npm from the release commit:

image

Resolving #15 will solve the immediate issue, but it's still a good idea to include the built files in the release commit imo.

Server Rendering

The component is very nice but could it support server rendering?

Option to clear URL hash

I'd like an option to clear the URL hash when I choose (i.e., when manually scrolling to the top of the page). Right now, the URL always contains a hash for the previously selected element, even when you refresh the page.

Add feature of not registering scroll event

Since scroll events are heavy, that would be grate if you could add the feature of disabling scroll event registration. This way I could have my own scroll event and pass it's pulses to many other components.

Don't highlight the first item until the user has reached it

I have the following sections on my page:

  1. intro
  2. skillset
  3. values
  4. showcase
  5. my-story

My navbar has a link for all of these items, except for intro, which I'm not using in this case:

<Scrollspy
  className="navbar-nav ml-auto"
  currentClassName="active"
  items={['skillset', 'values', 'showcase', 'my-story']}
  offset={-100}
>
  Links ...
</Scrollspy>

If the user is inside the intro section, but behind the skillset section, it'll apply the currentClassName to skillset (the first item in items). This shouldn't happen until the user is there.

Adding intro to the ScrollSpy (a link and item to its items prop) fixes this. So as a workaround I've done this but used display: none on it so it doesn't show.

Not working with nested components

Hi guys,

can NOT get it working, when using nested component like

const AffixLink = (props) => {
  const {
    src,
    title,
    href,
  } = props
  return (
    <div className="affix-link-wrapper col-xs-2">
      <a className="affix-link" href={href}>
        <div className="affix-link-img">
          <img className="img img-responsive" src={`/images/${src}`} alt=""/>
        </div>
        <div className="affix-link-title" dangerouslySetInnerHTML={{ __html: title }}/>
      </a>
    </div>
  )
}
return (
  <div className={`affix-toc-component ${cssClasses}`}>
    <Sticky id="asd" top="#navbar">
      <div className="container">
        <div className="row">
          <Scrollspy
            items={['anchor-1', 'anchor-2', 'anchor-3', 'anchor-4', 'anchor-5']}
            currentClassName="is-active"
            componentTag="div"
          >
            <AffixLink
              href="#anchor-1"
              />
            <AffixLink
              href="#anchor-2"
            />
          </Scrollspy>
        </div>
      </div>
    </Sticky>
  </div>
)

Coloring the anchor tag?

#Hi,

I tried to change the color of the anchor tags when it's active, but it didn't work since the styling is passed to the <li> tag? So is there a way where I can pass the class to the tags?

Thanks

Unable to Scroll to Div using <a href=“#”>]

I'm using this library to get the scroll to div effect.However after following the documentation ,I don't seem to get it working.Code :

<RewardContainer>
                <div className="pageWrapper">
                    <div className="rewardInfoWrapper">
                        <div className="tabsContainer">
                            <div>
                                <Scrollspy
                                    items={[
                                        "section-1",
                                        "section-2",
                                        "section-3"
                                    ]}
                                    currentClassName="is-current"
                                >
                                    <li>
                                        <a
                                            href="#section-1"
                                            className="c-side-nav__link"
                                        >
                                            Streak
                                        </a>
                                    </li>
                                    <li>
                                        <a
                                            href="#section-2"
                                            className="c-side-nav__link"
                                        >
                                            Gems
                                        </a>
                                    </li>
                                    <li>
                                        <a
                                            href="#section-3"
                                            className="c-side-nav__link"
                                        >
                                            Xp Points
                                        </a>
                                    </li>
                                </Scrollspy>
                            </div>
                        </div>
                        <div className="columnContainer">
                            <div className="tabInfo">
                                <div>
                                    <div id="section-1">
                                            <p>
                                                This is Section 1
                                            </p>
                                    </div>
                                    <div id="section-2">
                                            <p>
                                                This is Section 2
                                            </p>
                                        </div>
                                    <div id="section-3">
                                            <p>
                                                This is Section 3
                                            </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </RewardContainer>

The issue is ,my a href="#id" tag reloads the browser and treats id as a route instead of scrolling to that div's id.For instance,clicking on the third li element reloads the browser with http://localhost:7000/#section-3 in the url.

Module not found: ./throttle

react-scrollspy v3.0.2

After running an npm update I am getting the following error on a previously working Scrollspy:

Module not found: ./throttle

Uncaught Error: Cannot find module "./throttle"
at webpackMissingModule (scrollspy.js:52)
at Object. (scrollspy.js:52)
at webpack_require (bootstrap 922a4e6…:555)
at fn (bootstrap 922a4e6…:86)
at Object. (ExerciseSingle.js:5)
at webpack_require (bootstrap 922a4e6…:555)
at fn (bootstrap 922a4e6…:86)
at Object. (index.js:11)
at webpack_require (bootstrap 922a4e6…:555)
at fn (bootstrap 922a4e6…:86)

var _throttle = require('./throttle');

Add offset for content

Hi,

I have a fixed navbar at the top of my page. My content is on the left and my scrollspy is on the right. When I click on an element in scrollspy, my content scrolls to the correct id but the top bit of it is hidden by my nav bar. Offset doesn't work because it only offsets the scrollspy list.

Any ideas?

Can you add a offset

I have a request offset.
I'd like a offset which as bootstrap.
I try to add a value in the method ' _isInView', which can be used.
Uploading Screenshot from 2016-10-13 16:31:04.png…

how can i set a offsetTop of this component ?

because i have a fixed header on the page when i scroll down the page, so i want to set a offsetTop on this component to jump to the anchor point more precise, is there any ways to achieve ?

Support server-side rendering

The caching of window and document at the root level of this lib makes it so that it can't be rendered on the server. Just using the regular ol window and document should fix the problem.

List Items generated programmatically

Hi @makotot ,

first of all thanks for the beautiful component! I took a look at the issues unsuccessfully. I'd like to make react-scrollspy work together with programmatically generated list items. Could you plese provide me some info about the feasability. Thanks in advance. Here you'll find a reference code sample to give you a rough idea of what I'm talking:

const Parent = ({options}) => (
  <Scrollspy
    items={ ['news', 'mission', 'whatwedo', 'competences'] }
    currentClassName="active">
      {options.map((x, idx) => <Child item={x} key={idx}/>)}
  </Scrollspy>
);

const Child = ({item}) => (
  <li>
    <a href={item.anchor}>{item.label}</a>
  </li>
);

Remove unsupported node-4 build from Travis CI Builds - all builds failing due to node-4 build issue

I have seen that Pull Requests are all failing due to the node-4 build having an issue with yarn:
The command "eval yarn " failed

Example failure:
https://travis-ci.org/makotot/react-scrollspy/builds/499932228?utm_source=github_status&utm_medium=notification

Since nodejs.org doesn't support node 4 as of last year, it should not be used for Travis CI. Notice that in the example, all other builds are succeeding.

Not putting the class on li

I tried to do:

<Scrollspy items={this.getChildrenIds()} currentClassName="is-active"> {this.props.children} </Scrollspy>

and the children is:

<li> <a href={#${this.props.id}`}>
{this.props.children}

`

But the className is-active doesn't appear in the html generated.

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.