Search code examples
javascriptreactjsreact-virtualizeduse-ref

How do I scroll to a row in a list of rows using React?


I was using React-virtualized table and it has a very useful prop called scrollToIndex that was doing the job.

However, I had to get rid of the library and use my own JSX.

Now I have a big list of projects as follows:-

      render() {
        return(
          <div className="container">
            {projects.map(project => (
              <ProjectRow
                key={project.id}
                project={project}
              />
          ))}
   )};

Now let's assume projects array has more than 100 projects and I want to scroll initially to the middle of it, let's say project at index 50.

How to do that?

I tried using useRef() and createRef() on the div itself but without any scucess.


Solution

  • You can use scrollIntoView method to get into the specific position

    export default function App() {
      const [projects, setProjects] = useState([]);
      useEffect(() => {
        let p = [];
        for (let i = 0; i < 300; i++) {
          p.push({
            projectId: i,
            projectName: `Project ${i}`
          });
        }
        setProjects(p);
      }, []);
    
      function scrollTo(position) {
        const project = document.getElementById(position);
        project.scrollIntoView();
      }
    
      return (
        <div className="App">
          <button onClick={() => scrollTo(50)}>Scroll to 50</button>
          <button onClick={() => scrollTo(150)}>Scroll to 150</button>
          <button onClick={() => scrollTo(250)}>Scroll to 250</button>
          {projects.map((px, index) => (
            <Project
              key={index}
              projectName={px.projectName}
              projectId={px.projectId}
            />
          ))}
        </div>
      );
    }
    

    Please find the complete example in the codesandbox https://codesandbox.io/s/happy-jennings-o7tob