import React, { useLayoutEffect, useRef, useState } from 'react'; import Card from './components/Card'; import style from './styles/index.module.scss'; interface IRecommendationsProps { recommendations: any[]; } function Recommendations({ recommendations, }: IRecommendationsProps) { const [maxCardsOnDisplay, setMaxCardsOnDisplay] = useState(5); const [isOpen, setOpen] = useState(false); const ref = useRef() as React.MutableRefObject; useLayoutEffect(() => { const width = ref?.current?.offsetWidth; const placeForCard = (width - 30) / (220 + 24); setMaxCardsOnDisplay(placeForCard); }, []); const className = isOpen ? style.recommendations_full : style.recommendations_short; const children = (recommendations || []) .filter(item => item) .map((recommendation) => ( )); const visibleChildren = children.slice(0, isOpen ? Infinity : maxCardsOnDisplay); if (!children.length) return null; return (
{isOpen ? children : visibleChildren} {!isOpen && children.length > maxCardsOnDisplay && (
{ setOpen(true); }} > ยป
)}
); } export default Recommendations;