0

I use TypeScript and class component way and I need to save reference on my element. I am going to get the state of target element when 'resize' event will happen.

Accordingly How to use refs in React with Typescript I tried this:

export default class Carousel extends Component<CarouselProps, CarouselState> {
    private ref:  React.LegacyRef<HTMLDivElement>;
    constructor(...) {
        this.ref = React.createRef();
        window.addEventListener('resize', (e) => this.resizeCarouselElements());
    }
    componentDidUpdate(...){...}
    componentDidMount(...){...}
    resizeCarouselElements = () => {
        <...get current state of target element here ...>
    }
    render() {
        return (
            <div className='name' ref={this.ref}>
    })
}

But after resizing the window I have got null:

enter image description here

How can I save reference on my div className='name' and use it after user's window resizing? Which way is the best practice? Store the ref in state, const or somewhere else?

EaredGen
  • 91
  • 1
  • 1
  • 6
  • 1
    Is `this.stepInput` your ref name? Does this null value happens all the time or just the first time after the component mount? Also, you should move the line `window.addEventListener('resize', (e) => this.resizeCarouselElements());` to `componentDidMount` – Son Nguyen Jun 11 '22 at 18:38
  • 'this.ref' is my analogue of 'this.stepInput, yes. I moved 'addEventListener' to didMount as you said. Also I had mistake here: 'this.resizeCarouselElements())'. I called the method here instead of indicating. I had to write thios way: 'this.resizeCarouselElements'. After this corrects its works fine, thank you. – EaredGen Jun 12 '22 at 08:41

0 Answers0