How to use normal anchor links with react-router

后端 未结 3 1476
臣服心动
臣服心动 2020-12-02 18:38

Very similar to this angular question: how do I use anchor links for in-page navigation when using react-router?

In other words, how do I implement the following pla

相关标签:
3条回答
  • 2020-12-02 19:02

    import { Link } from 'react-router-dom'

    Link using

    <Link to='/homepage#faq-1'>Question 1</Link>

    Then insert the following code inside your target React component (Homepage):

    useEffect(() => {
        const hash = props.history.location.hash
        if (hash && document.getElementById(hash.substr(1))) {
            // Check if there is a hash and if an element with that id exists
            document.getElementById(hash.substr(1)).scrollIntoView({behavior: "smooth"})
        }
    }, [props.history.location.hash]) // Fires every time hash changes
    
    0 讨论(0)
  • 2020-12-02 19:11

    React Router Hash Link worked for me. Easy to install and implement:

    $ npm install --save react-router-hash-link
    

    In your component.js import it as Link:

    import { HashLink as Link } from 'react-router-hash-link';
    

    And instead of using an anchor <a>, use <Link> :

    <Link to="#faq-1>Question 1</Link>
    <Link to="#faq-2>Question 2</Link>
    <Link to="#faq-3>Question 3</Link>
    

    NOTE: I used HashRouter instead of Router

    0 讨论(0)
  • 2020-12-02 19:22

    The problem with anchor links is that react-router's default is to use the hash in the URL to maintain state. Fortunately, you can swap out the default behaviour for something else, as per the Location documentation. In your case you'd probably want to try out "clean URLs" using the HistoryLocation object, which means react-router won't use the URL hash. Try it out like this:

    Router.run(routes, Router.HistoryLocation, function (Handler) {
      React.render(<Handler/>, document.body);
    });
    
    0 讨论(0)
提交回复
热议问题