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.

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
this helps with the css issues I found. stackoverflow.com/questions/11039885/… Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.