Setting div height based on height of child div in React

21 views Asked by At

I am attempting to create a carousel to display blog slides in React. I have it essentially working but I've had some issues with setting the height of the carousel track div, which I have setup to accommodate the height of the absolutely-positioned blog slides (which are, of course, children divs of the track).

const CarouselV3 = ({content, topMovies, container}) => {

    const slideRef = useCallback(node => {
        if (node !== null) {
            setCarouselHeight(node.getBoundingClientRect().height);
        }
    }, []);

    const [carouselHeight, setCarouselHeight] = useState(0);

    return ( 
        <div className="carouselV3">
            <div className="track_containerV3">
                <div className="carouselV3_track"
                style={{height: `${carouselHeight}px`}}>
                    {content && content.map((blog, index) => {
                        return <motion.div className={index == carouselActiveIndex ? "blogSlide-active blogSlide" : "blogSlide"}
                        ref={slideRef}
                            <h3>Reviewed by {blog.name} on {blog.date.slice(0,10)}</h3>
                            <img 
                            src={topMovies && topMovies.find((movie) => movie.title == blog.movie).image} alt=""/>
                            <p>{blog.aggRating}</p>
                        </motion.div>
                    })}
                </div>
            </div>
        </div>
     );
}
 
export default CarouselV3;

I have set my slideRef up with a useCallback function, with the intention that it will update carouselHeight with the slide's height when rendered. Initially, I thought this was working, but when I cleared my cache and refreshed my page the carousel did not set at the correct height. The slides were the size they should be, but it looked like the the callback function was not firing. However, when I added a console log to the callback function:

const slideRef = useCallback(node => {
        if (node !== null) {
            setCarouselHeight(node.getBoundingClientRect().height);
            console.log( carouselHeight);
        }
    }, []);

I can see that the callback function is calling, but it is not updating carouselHeight with the height of the blog slide. carouselHeight is logged 10 times (I have 10 blog slides), but it remains at 0. However if I then refresh the page, the carousel height is set correctly to accommodate the blog slides.

Admittedly this is my first time using useCallback - can someone help point me in the right direction? Many thanks in advance.

0

There are 0 answers