0

Есть задача, по нажатию на кнопку скролл прокручивается до определенного блока. Создал ref и функцию на наведение на блок, у которого есть 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>

А если будет несколько блоков, как для каждого ref'a, сделать это в виде массива?

<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>
1
  • у каждого отдельного элемента свой ref, поэтому использование массива вполне логично.
    – Grundy
    18 окт 2022 в 10:22

1 ответ 1

-1

Помогли с решением, если кому понадобится, оставлю тут)

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>
    ));

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.