Access an element not yet rendered in ReactJS

36 views Asked by At

In my React application, I have a DataGrid component from MUI with 100 rows. Due to virtualization, it only renders a subset of those rows. In this example the first 12 rows.

<div>
  <div data-id="1">...</div>
  <div data-id="2">...</div>
  <div data-id="3">...</div>
  <div data-id="4">...</div>
  <div data-id="5">...</div>
  <div data-id="6">...</div>
  <div data-id="7">...</div>
  <div data-id="8">...</div>
  <div data-id="9">...</div>
  <div data-id="10">...</div>
  <div data-id="11">...</div>
  <div data-id="12">...</div>
</div>

If I scrolled down, the rendered rows and their data are updated accordingly, like so:

<div>
  <div data-id="45">...</div>
  <div data-id="46">...</div>
  <div data-id="47">...</div>
  <div data-id="48">...</div>
  <div data-id="49">...</div>
  <div data-id="50">...</div>
  <div data-id="51">...</div>
  <div data-id="52">...</div>
  <div data-id="53">...</div>
  <div data-id="54">...</div>
  <div data-id="55">...</div>
  <div data-id="56">...</div>
</div>

My current dilemma is I need to scroll to a particular row. I am using the code below. The rows have to be sorted in ascending order of their data-id.

const selectedRow = document.querySelector(`div[data-id='${id}']`);
selectedRow?.scrollIntoView({ behavior: "smooth" })

If the row with the given data-id is rendered, it will scroll into it just fine, however if for example the value id=98, it will be null since that particular row is not yet rendered. Are there possible solutions or workarounds for this problem?

0

There are 0 answers