I'm trying to write Reactjs code for scroll to functionality. I want the referenced IDs of different sections be generated for the elements of the 'lables' array.
import { useRef } from 'react';
const useDivRefs = (labels) => {
const divRefs = {};
labels.forEach((label, i) => {
const targetId = label.replace(/\s+/g, '');
const ref = useRef(null);
divRefs[targetId] = ref;
});
return divRefs;
};
const MyComponent = () => {
const labels = [
'div 1',
'div 2',
'div 3',
];
const divRefs = useDivRefs(labels);
console.log('divRefs = ', divRefs);
return divRefs;
};
it works, but the line "const ref = useRef(null); " shows the following error
"React Hook "useRef" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks"
how can I get rid of this error? Any help would be appreciated.