커스텀 훅
import { useCallback, useState } from 'react';
import { LayoutChangeEvent, LayoutRectangle } from 'react-native';
interface Return {
layout: LayoutRectangle | undefined;
onLayout: (event: LayoutChangeEvent) => void;
}
export const useGetLayout = (): Return => {
const [layout, setLayout] = useState<LayoutRectangle>();
const onLayout = useCallback((event: LayoutChangeEvent) => {
setLayout(event.nativeEvent.layout);
}, []);
return { layout, onLayout };
};
사용 예시
...
export function GridCellList<DataType>({
data,
renderItem,
numColumns,
spaceBetweenRow,
}: Props<DataType>): ReactElement {
const { layout: wrapperLayout, onLayout: onWrapperLayout } = useGetLayout();
const { layout: cellLayout, onLayout: onCellLayout } = useGetLayout();
...
// onLayout으로 얻은 값으로 계산하는 로직
const spaceBetweenColumn =
wrapperLayout && cellLayout
? (wrapperLayout?.width - cellLayout?.width * numColumns) /
(numColumns - 1)
: 0;
...
<Cell
// eslint-disable-next-line react/no-array-index-key
key={`UserCell${index}`}
onLayout={onCellLayout}
spaceBetweenColumn={spaceBetweenColumn}
>
{renderItem(item, i * numColumns + index, data)}
</Cell>
);
});
...
return <Wrapper onLayout={onWrapperLayout}>{rows}</Wrapper>;
}
...