javascriptreactjsrefs

ReactJS .map with a ref to each component


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?


Solution

  • 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