4

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.

Ziko
  • 919
  • 2
  • 10
  • 22

1 Answers1

3

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

Aamin Khan
  • 712
  • 4
  • 12
  • This works good but I see the CSS gets messed up at the end and the top of my page when the scroll happens. Let me see if I can fix that. – Ziko Apr 06 '21 at 20:35
  • this helps with the css issues I found. https://stackoverflow.com/questions/11039885/scrollintoview-causing-the-whole-page-to-move/11041376 Thanks! – Ziko Apr 06 '21 at 20:37