Malek Hammad
Malek Hammad

Reputation: 51

How do I use react router and react scroll on the same button?

I want to use a react-router and a react-scroll on the same Nav link. If I am on the home page I want the button to have the react scroll behavior. If I am on a different page the button needs go back to the home page and then scroll to the preferred component(react-scroll behavior)

This is what I thought off but it doesn't work properly.

import { Link } from 'react-router-dom';
import { Link as LinkRoll } from 'react-scroll'

                           <Link
                               to='/'
                               className='nav-links'
                           >
                               <LinkRoll
                                   activeClass='active'
                                   to='about'
                                   spy={true}
                                   smooth={true}
                                   offset={-70}
                                   duration={500}
                                   onClick={closeMobileMenu}
                               >
                                   About
                               </LinkRoll>
                           </Link>

Upvotes: 4

Views: 3489

Answers (1)

MB_
MB_

Reputation: 1747

App.js

import React from 'react';
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
import './style.css';

import Navigation from './Navigation';
import Home from './Home';
import Other from './Other';

export default function App() {
  return (
    <Router>
      <Navigation />
      <Route path="/home">
        <Home />
      </Route>
      <Route path="/other">
        <Other />
      </Route>
      <Route exact path="/">
        <Redirect to="/home" />
      </Route>
    </Router>
  );
}

Navigation.js

import React from 'react';
import { NavLink, useLocation, useHistory } from 'react-router-dom';
import * as Scroll from 'react-scroll';

export default function Navigation() {
  const path = useLocation().pathname;
  const location = path.split('/')[1];
  const history = useHistory();
  const scroller = Scroll.scroller;

  const scrollToAnchor = () => {
    scroller.scrollTo('anchor', {
      duration: 1500,
      delay: 100,
      smooth: true,
      offset: 50
    });
  };

  const goToHomeAndScroll = async () => {
    await closeMobile();
    await history.push('/');
    await scroller.scrollTo('anchor', {
      duration: 1500,
      delay: 100,
      smooth: true,
      offset: 50
    });
  };

  const closeMobile = () => {};

  return (
    <div className="container">
      <div className="navigation">
        <NavLink to="/home" activeClassName="active">
          Home
        </NavLink>
        <NavLink to="/other" activeClassName="active">
          Other Page
        </NavLink>
      </div>
      {location === 'home' ? (
        <button onClick={scrollToAnchor}>Scroll to anchor</button>
      ) : (
        <button onClick={goToHomeAndScroll}>
          Go to Home and Scroll to anchor
        </button>
      )}
    </div>
  );
}

Home.js

import React from 'react';
import * as Scroll from 'react-scroll';

export default function Home() {
  const Element = Scroll.Element;

  return (
    <div>
      <h1>Home</h1>
      <p>Welcome</p>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed gravida
        fermentum purus egestas blandit. Nam nisl sem, feugiat hendrerit magna
        non, ullamcorper pharetra nibh. Sed vestibulum nisi enim, non bibendum
        lorem aliquam non. Cras turpis risus, elementum a sapien quis, dictum...
      </p>
      <p>
        Sed volutpat, turpis vitae cursus viverra, quam tortor maximus felis,
        tempus eleifend nulla metus et sapien. Curabitur vitae sodales dolor.
        Phasellus a ultrices felis. Aenean efficitur nibh sit amet tortor...
      </p>
      <Element name="anchor">
        Nam nisi nisi, aliquet at blandit et, pulvinar sit amet quam. Sed
        euismod ex dui, posuere tristique purus tincidunt in. Orci varius
        natoque penatibus et magnis dis parturient montes, nascetur ridiculus
        mus. Vestibulum sit amet nisi commodo, pretium quam non, scelerisque...
      </Element>
    </div>
  );
}

Other.js

import React from 'react';

export default function Other() {
  return (
    <>
      <h1>Other page</h1>
      <p>blablabla</p>
    </>
  );
}

Demo : Stackblitz

Same result without react-scroll : Stackblitz

Upvotes: 3

Related Questions