20

I have two <Route>s created with react-router.

  • /cards -> List of cards game
  • /cards/1 -> Detail of card game #1

When the user clicks on the "Return to list", I want to scroll the user where he was on the list.

How can I do this?

Roy Scheffers
  • 3,255
  • 10
  • 28
  • 33
Sancho
  • 981
  • 1
  • 15
  • 39

4 Answers4

21

Working example at codesandbox

React Router v4 does not provide out of the box support for scroll restoration and as it currently stands they won't either. In section React Router V4 - Scroll Restoration of their docs you can read more about it.

So, it's up to every developer to write logic to support this although, we do have some tools to make this work.

element.scrollIntoView()

.scrollIntoView() can be called on an element and as you can guess, it scrolls it into view. Support is quite good, currently, 97% of browsers support it. Source: icanuse

The <Link /> component can pass on state

React Router's Link component has a to prop which you can provide an object instead of a string. Here's who this looks.

<Link to={{ pathname: '/card', state: 9 }}>Card nine</Link>

We can use state to pass on information to the component that will be rendered. In this example, state is assigned a number, which will suffice in answering your question, you'll see later, but it can be anything. The route /card rendering <Card /> will have access to the variable state now at props.location.state and we can use it as we wish.

Labeling each list item

When rendering the various cards, we add a unique class to each one. This way we have an identifier that we can pass on and know that this item needs to be scrolled into view when we navigate back to the card list overview.

Solution

  1. <Cards /> renders a list, each item with a unique class;
  2. When an item is clicked, Link /> passes the unique identifier to <Card />;
  3. <Card /> renders card details and a back button with the unique identifier;
  4. When the button is clicked, and <Cards /> is mounted, .scrollIntoView() scrolls to the item that was previously clicked using the data from props.location.state.

Below are some code snippets of various parts.

// Cards component displaying the list of available cards.
// Link's to prop is passed an object where state is set to the unique id.
class Cards extends React.Component {
  componentDidMount() {
    const item = document.querySelector(
      ".restore-" + this.props.location.state
    );
    if (item) {
      item.scrollIntoView();
    }
  }

  render() {
    const cardKeys = Object.keys(cardData);
    return (
      <ul className="scroll-list">
        {cardKeys.map(id => {
          return (
            <Link
              to={{ pathname: `/cards/${id}`, state: id }}
              className={`card-wrapper restore-${id}`}
            >
              {cardData[id].name}
            </Link>
          );
        })}
      </ul>
    );
  }
}

// Card compoment. Link compoment passes state back to cards compoment
const Card = props => {
  const { id } = props.match.params;
  return (
    <div className="card-details">
      <h2>{cardData[id].name}</h2>
      <img alt={cardData[id].name} src={cardData[id].image} />
      <p>
        {cardData[id].description}&nbsp;<a href={cardData[id].url}>More...</a>
      </p>
      <Link
        to={{
          pathname: "/cards",
          state: props.location.state
        }}
      >
        <button>Return to list</button>
      </Link>
    </div>
  );
};

// App router compoment.
function App() {
  return (
    <div className="App">
      <Router>
        <div>
          <Route exact path="/cards" component={Cards} />
          <Route path="/cards/:id" component={Card} />
        </div>
      </Router>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Roy Scheffers
  • 3,255
  • 10
  • 28
  • 33
  • 5
    this answers the question but does not solve the problem when users click on the browser back button – Damien Aug 07 '19 at 11:59
2

Since there is no answer for how to do this in a functional component, here's a hook solution I implemented for a project:

import React from 'react';
import { useHistory } from 'react-router-dom';

function useScrollMemory(): void {
  const history = useHistory<{ scroll: number } | undefined>();

  React.useEffect(() => {
    const { push, replace } = history;

    // Override the history PUSH method to automatically set scroll state.
    history.push = (path: string) => {
      push(path, { scroll: window.scrollY });
    };
    // Override the history REPLACE method to automatically set scroll state.
    history.replace = (path: string) => {
      replace(path, { scroll: window.scrollY });
    };

    // Listen for location changes and set the scroll position accordingly.
    const unregister = history.listen((location, action) => {
      window.scrollTo(0, action !== 'POP' ? 0 : location.state?.scroll ?? 0);
    });

    // Unregister listener when component unmounts.
    return () => {
      unregister();
    };
  }, [history]);
}

function App(): JSX.Element {
  useScrollMemory();

  return <div>My app</div>;
}

With this override solution, you need not to worry about passing the state in all of your Link elements. An improvement would be making it generic so it's backwards compatible with the push and replace methods of history but it wasn't a requirement in my particular case so I omitted it.

I'm using react-router-dom but you could just as easily override the methods of the vanilla historyAPI.

Shortchange
  • 81
  • 1
  • 3
1

One other possible solution to this is to render your /cards/:id route as a full screen modal and keep the /cards route mounted behind it

Jon Wyatt
  • 1,086
  • 8
  • 12
1

For full implementation using Redux you can see this on CodeSandbox.

I did this by utilizing the history API.

  1. Save scroll position after a route change.

  2. Restore the scroll position when the user clicks the back button.

Save the scroll position in getSnapshotBeforeUpdate and restore it in componentDidUpdate.

  // Saving scroll position.
  getSnapshotBeforeUpdate(prevProps) {
    const {
      history: { action },
      location: { pathname }
    } = prevProps;

    if (action !== "POP") {
      scrollData = { ...scrollData, [pathname]: window.pageYOffset };
    }

    return null;
  }

  // Restore scroll position.
  componentDidUpdate() {
    const {
      history: { action },
      location: { pathname }
    } = this.props;

    if (action === "POP") {
      if (scrollData[pathname]) {
        setTimeout(() =>
          window.scrollTo({
            left: 0,
            top: scrollData[pathname],
            behavior: "smooth"
          })
        );
      } else {
        setTimeout(window.scrollTo({ left: 0, top: 0 }));
      }
    } else {
      setTimeout(window.scrollTo({ left: 0, top: 0 }));
    }
  }
Agus Syahputra
  • 386
  • 3
  • 12
  • This solution worked for me with a couple of minor mods. Instead of updating the scrollData object in getSnapshotBeforeUpdate, I bound a debounced event handler to the "scroll" event so that I was not updating scrollData as frequently. I also modified the componentDidUpdate function so that I'd only scroll the window when pathname !== prevProp.location.pathname, so that I didn't scroll the window for updates due to other non-path related property changes. – tlfu Nov 06 '19 at 12:17
  • Why do you need a setTimeout in the code above? – vijayst Feb 25 '21 at 16:48