Search code examples
javascriptjs-scrollintoview

scrollIntoView() doesn't scroll anywhere


I can't get Element.scrollIntoView() to work. I have the code below. There are two locations that it should scroll to, depending on some variable. However, it doesn't scroll to either of them. What am I doing wrong?

class Page extends Component {
    scrollToMyRef = (id) => {
        var ref = document.getElementById(id);
        console.log("Ref1: " + ref);            // returns [object HTMLElement]
        console.log("Ref2: " + document.ref);   // returns undefined
        console.log("Id: " + id);               // returns myRef
        ref.scrollIntoView({
            behavior: "smooth",
            block: "start",
        });
    };

    componentDidMount() {
        if (this.props.location.state) {
            if (this.props.location.state.origine) {
                this.scrollToMyRef("myRef");
            } else {
                this.scrollToMyRef("myTopRef");
                });
            }
        }
    }

    render() {
        return (
            <div
                id="myTopRef"
                key="pricing"
                className="pricing"
            >
                ...
            </div>
            <section id=myRef className="section">
                ...
            </section>
            ...
        )
    }

Solution

  • After setting a time delay it worked:

    scrollToMyRef = (id) => {
          var ref = document.getElementById(id);
          setTimeout(function () {
               ref.scrollIntoView({
                   behavior: "smooth",
                   block: "start",
               });
          }, 100);
    };