How to use normal anchor links with react-router

后端 未结 3 1487
臣服心动
臣服心动 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

    Question 1

    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
    

提交回复
热议问题