Reputation: 81
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.
src > components > shoes > shoe.tsx (where the magic happens)
Upvotes: 0
Views: 118
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