Brent Anderson
Brent Anderson

Reputation: 81

can't use react ref to dynamically set distance

github: https://github.com/Brent-W-Anderson/shoe_store/tree/main

Hi, I need help using my react ref correctly. I'm creating an image slider and I'm centering the first image in the set based on the image width (which is based on a height all of the images share --which means the widths are different from image to image).

When my component mounts, the ref width is undefined (I'm assuming because it's not mounted yet? but I can't figure it out). I know this should work because I'm setting a "resize" event within the same componentDidMount function and as soon as I go to resize the window ( or after some time passes ), then the width of each image is showing exactly as it should be.

on initial page load:

after resizing the window:

src > components > shoes > shoe.tsx (where the magic happens) enter image description here

Upvotes: 0

Views: 118

Answers (1)

Nicholas Mberev
Nicholas Mberev

Reputation: 1851

Please do this and let me know the outcome. There could be weird behavior with classes without constructors. Also check this: why we write super props for reasons behind use of constructors.

export default class Shoe extends Component<{ shoe: { asset:string, name:string, price:number }, handleShoePos:Function }> {
     // add this 
    constructor(props){ // use some tsx behavior if you want
      super(props);
      this.cardRef = React.createRef<HTMLDivElement>();
    }
    
    componentDidMount() {
        window.addEventListener( 'resize', this.handleResize );

        this.handleResize();
    }

    handleResize = () => {
        const { handleShoePos } = this.props;
        const width = this.cardRef.current?.clientWidth;

        if( width ) {
            handleShoePos( width / 2 );
        }
    }

    render() {
        const { asset, name, price } = this.props.shoe;

        return (
            <div ref={ this.cardRef } className="shoe_card">
                ......
            </div>
        );
    }
}

Upvotes: 0

Related Questions