'I define column index parameter in my arrow function but i can use in my useEffect causes is not define
I define column index parameter in my arrow function but I can use in my useEffect causes is not define! What can I do?
useEffect(() => {
const resizeObserver = new ResizeObserver(() => {
if (elementRef.current) {
setBoxViewWidth(elementRef.current.clientWidth);
if (elementRef.current.clientWidth < 1200) {
elementRef.current.clientWidth.style.right = (boxViewWidth / 2) * (columnIndex % 2);
} else if (elementRef.current.clientWidth < 992) {
elementRef.current.clientWidth.style.right = (boxViewWidth / 1) * (columnIndex % 1);
}
}
});
if (elementRef.current) {
resizeObserver.observe(elementRef.current);
}
return () => {
resizeObserver.disconnect();
};
}, [boxViewWidth]);
const RenderBox = ({ style, rowIndex, columnIndex }) => {
console.log(style);
return (
rows && (
<div
style={{
...style,
right: (boxViewWidth / 3) * (columnIndex % 3),
}}
>
......
Solution 1:[1]
There are a couple of problems here:
columnIndexreferenced in theuseEffecthook will be undefined, that is because the value of it will only be available in the context ofRenderBox. So we need a different way to pass it. We can use andata-*attribute to achieve that easily.- the value in the dependencies array passed to
useEffect(I'm referring toboxViewWidth) might not be enough to account for all component updates. We'll also needelementRef.current boxViewWidthis updated twice with each run. This is not a huge issue here, but we can fix that too.- there is no such thing as
HTMLElement.clientWidth.style.right, I think we wantHTMLElement.style.right, fixing that too.
The code then becomes:
React.useLayoutEffect(() => {
function updateBoxViewWidth() {
if (!elementRef.current) return
if (elementRef.current.clientWidth === boxViewWidth) return
setBoxViewWidth(elementRef.current.clientWidth)
}
updateBoxViewWidth()
}, [elementRef.current, boxViewWidth])
useEffect(() => {
const resizeObserver = new ResizeObserver(() => {
if (!elementRef.current) return
const columnIndex = elementRef.current.getAttribute('data-column-index');
if (elementRef.current.clientWidth < 1200) {
elementRef.current.style.right = (boxViewWidth / 2) * (columnIndex % 2);
} else if (elementRef.current.clientWidth < 992) {
elementRef.current.style.right = (boxViewWidth / 1) * (columnIndex % 1);
}
});
if (elementRef.current)
resizeObserver.observe(elementRef.current);
return () => {
if (elementRef.current)
resizeObserver.disconnect();
};
}, [elementRef.current, boxViewWidth]);
const RenderBox = ({ style, rowIndex, columnIndex }) => {
console.log(style);
return (
rows && (
<div
data-column-index={columnIndex}
style={{
...style,
right: (boxViewWidth / 3) * (columnIndex % 3),
}}
>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Silviu-Marian |
