0

Working on making it so when a user goes back a page in my react app they will be scrolled to the position on the page they were previously at. Specifically, to the item on a list that they had clicked on.

Current approach is to use the below const scrollToRef = (ref) => window.scrollTo(0, ref.current.offsetTop)

alongside redux tracking the ref to scroll to & a useEffect hook to scroll to that ref on page load.

however I can't seem to get any refs assigned with my .map.

const refs = React.useRef(React.createRef());




      {displayUnavail && !displaySearch
        ? notAvailable.map((tracker) => (
            <IndividualTracker ref={refs.current[tracker]} tracker={tracker} key={tracker.pim} history />
          ))
        : null}

Is the issue because i'm doing this on a component directly?

1 Answers1

1

Create an empty object to hold your refs.

const allTheRefs = {}

Then in each map iteration, write the ref to that object, with using the map key as the object key

{displayUnavail && !displaySearch && 
  notAvailable.map((tracker) => (
    <IndividualTracker ref={ref => allTheRefs[tracker.pim] = ref } ... />
  )
}

Once your map statement is executed, your allTheRefs variable will contain all the refs as key value pairs, with the keys being the tracker.pim value, and the value being the ref itself.

Here is a working codesandbox

Seth Lutske
  • 9,154
  • 5
  • 29
  • 78
  • Thank you for your answer. However this doesn't seem to work. allTheRefs remains empty even after the .map is executed – KleinBottleCode Jul 24 '20 at 14:00
  • I'm not sure of the overall structure of your code - perhaps you can post more for context. What kind of component are you using? My answer was for use in a functional component. If you're inside of a class component, you'll have to write it as `allTheRefs = {}`, and `ref={ref => this.allTheRefs[tracker.pim] = ref }`. Make sure your `const allTheRefs = {}` or `allTheRefs = {}` is declared at the root level of your function or class scope. – Seth Lutske Jul 24 '20 at 15:06
  • Functional component. allTheRefs is declared at root level of the component – KleinBottleCode Jul 24 '20 at 17:11
  • {displayUnavail && !displaySearch ? notAvailable.map((tracker) => allTheRefs[tracker.pim] = ref } id={tracker.pim} tracker={tracker} key={tracker.pim} history />) : null} – KleinBottleCode Jul 24 '20 at 17:11
  • Refs is just an empty object when page finishing rendering – KleinBottleCode Jul 24 '20 at 17:13
  • Its hard to say what's going wrong without more code. Where are you checking the value of your refs? [Here](https://codesandbox.io/s/refs-in-a-map-statement-hp8cc) is a simple working codesandbox. I'll add it to the answer as well. – Seth Lutske Jul 24 '20 at 18:30
  • Just wanted to say thanks for your detailed help with this issue way back when, I was a baby, baby dev in over my head. – KleinBottleCode May 17 '21 at 11:37