Home > Back-end >  How to make array from ref in react typescript
How to make array from ref in react typescript

Time:10-20

There is a task, by pressing the button, the scroll scrolls to a certain block. I created a ref and a function to scroll to a block that has a ref:

const myRef = React.useRef(null);

const executeScroll = () => (myRef.current.scrollIntoView());

.........

<div onClick={() => executeScroll()} className={styles.contentChapter}></div>

.........

<div ref={myRef} className={styles.chapter}><b>123</b></div>

And if there are several blocks, how for each ref'a, do it as an array?

<div ref={myRef} className={styles.chapter}><b>123</b></div>
<div ref={myRef} className={styles.chapter}><b>234</b></div>
<div ref={myRef} className={styles.chapter}><b>345</b></div>

CodePudding user response:

You can try creating an addToRef function like this

const refArray = useRef<HTMLDivElement[]>([]);
const addToRefs = useCallback((el: HTMLDivElement | null, index: number) => {
    if (!el || refArray.current.includes(el)) return;
    refArray.current.splice(index, 0, el);
  }, []);
...
// Then use the array index with the scroll handler function
const executeScroll = (index :number) => (refArray.current?.[index]?.scrollIntoView());
...

return yourArray.map((d, index) => (
    <div
      key={d.id}
      ref={(ele) => {
        addToRefs(ele, index);
      }}
    >
      {d.yourProperty}
    </div>
  ));
  • Related