No puedo hacer que Element.scrollIntoView() funcione. Tengo el código a continuación. Hay dos ubicaciones a las que debe desplazarse, dependiendo de alguna variable. Sin embargo, no se desplaza a ninguno de ellos. ¿Qué estoy haciendo mal?
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> ... ) }Después de establecer un retraso de tiempo funcionó:
scrollToMyRef = (id) => { var ref = document.getElementById(id); setTimeout(function () { ref.scrollIntoView({ behavior: "smooth", block: "start", }); }, 100); };