javascriptreactjsreact-router

Null ref after switching route in React


Stop training AI on contributed content


Solution

  • I suspect that your component is recreated when you go to a new route again, but the old listener is still invoked by the resize handler. Try to remove event listener in componentWillUnmount:

    componentDidMount() {
        this.setCaretVis();
        window.addEventListener("resize", this.setCaretVis);
        this.setCaretVis();
    }
    
    componentWillUnmount() {
        window.removeEventListener("resize", this.setCaretVis);
    }
    

    When router recreates the component, it will subscribe to resize event again.

    From the docs:

    componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any DOM elements that were created in componentDidMount