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),
}}
>
......
There are a couple of problems here:
columnIndex
referenced in theuseEffect
hook 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.useEffect
(I'm referring toboxViewWidth
) might not be enough to account for all component updates. We'll also needelementRef.current
boxViewWidth
is updated twice with each run. This is not a huge issue here, but we can fix that too.HTMLElement.clientWidth.style.right
, I think we wantHTMLElement.style.right
, fixing that too.The code then becomes: