Adèle
Adèle

Reputation: 31

How to handle click on details (and navigate back on list) with infinite list item?

I have an infinite scroll which displays items When I click on one item it opens the detail page When I go back to the infinite scroll/list page I need to go back to the item I just clicked on, not to the top How can I do that ?

Few ideas: Should I use an anchor link or some equivalent to choose the item I want to go back to ? Should I display the detail page on top of the list ?

Some details: The infinite scroll is paged and can received thousands of items I'm working with ReactJS

Thank you !

Upvotes: 0

Views: 429

Answers (1)

KawaLo
KawaLo

Reputation: 2294

You can use the scrollIntoView function, which achieve exactly what you want. Let’s say all of your items are identified by an unique id :

rendered HTML

<div id="container">
  . . .
  <element id="1897">

  </element>
</div>

And your list is at http://localhost:3001/my_url/list. Clicking on your element brings you to the following address : http://localhost:3001/mu_url/item/1897.

Then, inside your element model, your link to go back to the main page should look something like this :

item.jsx

<Link
  . . .
  to={{
    pathname: `/my_url/list?lastPosition=${this.state.id}`
  }}
>

Notice that we added an URL parameter on our back button. Replace this.state.id with the reference to your current item id, if it isn’t here. Then, in your main component, you can add the following :

container.jsx

import React from ‘react’;
. . .

class Container extends React.Component {
  constructor(props) {. . .}

  // React function that trigger once your component is mounted
  componentDidMount() {
    const url = new URL(window.location.href);
    const lastPosition = url.searchParams.get(‘lastPosition’);

    if (lastPosition && element) {
      const element = document.querySelector(`#${lastPosition}`);
      element.scrollIntoView();
    }
  }

  . . .

  render() {
    . . .
  }
}

Thus, if an element id is given as an URL parameter AND an element is find with id matching this parameter, your window with automatically scroll to it. Plus, this allow you to send the link to other people, which will not have to scroll to find the item.

Upvotes: 2

Related Questions