javascriptreactjsreact-routerreact-scroll

React scroll with redirect to other route path


I have a problem with my page that I build. There is main route path like "/" where is all page but there is also route path "/privacy" where you can go by clicking button "Privacy policy". Main navigation and footer with navigation are displaying at "/" and "/privacy" also.

It looks like this:

        <Route exact path="/">
            <Header />
            <Main />
            <Footer />
        </Route>
        <Route path="/privacy">
            <Header />
            <Privacy />
            <Footer />
        </Route>

The Main component looks like this

const Main = () => {


return (
    <>
        <Hello />
        <Services />
        <Projects />
        <About />
        <Contact />
    </>
)}

All buttons in nav are react-scroll links.

         <ul>
            <li><Link to="header" smooth="true" duration={1000}>Main</Link></li>
            <li><Link to="services" smooth="true" duration={1000}>Services</Link></li>
            <li><Link to="webdev" smooth="true" duration={1000}>Portfolio</Link></li>
            <li><Link to="about" smooth="true" duration={1000}>About</Link></li>
            <li><Link to="contact" smooth="true" duration={1000}>Contact</Link></li>
         </ul>

How can I redirect user from "/privacy" and scroll to - for example - about component at my "/" route path when he clicks "About" button in nav?

Example:

User is at "/privacy" and he wants to read "About" section, so he clicks button "About" in nav and then website is redirecting to "/" and scrolling to "About" section.


Solution

  • So. Add to component / root element of component about id="about" and then in your link set path <Link to="/#about"...... You can find info how to make links to content on the same page here (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a)