react-scroll | How to scroll to a specific targeted component when clicking on Navbar Link

前端 未结 2 993
感情败类
感情败类 2020-12-18 08:58

I am making a single scroller page using React and want to navigate to a specific section of the page. In HTML we use an href and anchor tag to achieve this interaction.

相关标签:
2条回答
  • 2020-12-18 09:34

    Other Alternative:

    Put an id in component that you want to go:

    <div id='some-id'>
    </div>
    

    After that, call from any place:

    const anchor = document.querySelector('#some-id')
    anchor.scrollIntoView({ behavior: 'smooth', block: 'center' })
    
    0 讨论(0)
  • 2020-12-18 09:43

    react-scroll is a great library - let me try and explain how I understand it.

    Wherever I need a Link that scrolls to a certain element, I import that link, define it, and render it:

    import React, { Component } from 'react'
    import Scroll from 'react-scroll'
    const ScrollLink = Scroll.ScrollLink
    
    class Navbar extends Component {
    
    render() {
      return (
        <nav>
          <ScrollLink 
            to="example-destination" 
            spy={true} 
            smooth={true} 
            duration={500} 
            className='some-class' 
            activeClass='some-active-class'
          >
            Link Text Goes Here
          </ScrollLink>       
        </nav>
      )
    }
    
    export default Navbar;
    

    In a separate file, we define the destination that the `Link` will scroll to. The `Element` import from react-scroll makes this pretty easy!

    import React, { Component } from 'react'
    import { Element } from 'react-scroll'
    
    export default function () {
      return (
        <React.Fragment>
        
          <Element id='example-destination' name='example-destination'>
            // wrap your content in the Element from react-scroll
          </Element>
    
        </React.Fragment>
      )
    }
    

    Making sense? Let me know if I can expand on this further!

    0 讨论(0)
提交回复
热议问题