0

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

1 Answers1

0

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>
        );
    }
}
Nicholas Mberev
  • 1,563
  • 1
  • 14
  • 14
  • Dang I was really hopeful with this answer, but it didn't work! I ended up fixing this by creating a timing function that calls itself after 1ms if it didn't grab the right values. ( I didn't like this answer so I changed the design entirely ). I'm still hopeful for an answer, though! – Brent Anderson Feb 01 '22 at 02:34
  • I could not run your app after cloning it from Github, Please could you package it and send it to me directly to help you check ? so that we can fix it and update the answer. Or could you update with all project files your git repo? – Nicholas Mberev Feb 01 '22 at 04:49