javascriptreactjsnulljs-scrollintoviewcreate-ref

ScrollIntoView() can find the html element


I'm trying to create a scroll to element but I'm getting this error

"TypeError: Cannot read property 'scrollIntoView' of null". By console logging mapRef I can see that I'm getting the correct div. console.log

export class FinderComponent extends PureComponent {
  constructor(props) {
    super(props);
    this.mapRef = React.createRef();
  }

  renderMap() {
    return <div block="StoreFinder" ref={this.mapRef}></div>;
  }

  renderStoreCard(store) {
    this.mapRef.current.scrollIntoView({ behavior: "smooth" });
    //console.log(this.mapRef.current);
    return (
      <div
        block="StoreFinder"
        elem="Store"
        key={store_name.replace(/\s/g, "")}
        mods={{ isActive: store_name === selectedStoreName }}
      >
        {this.renderStoreCardContent(store)}
        <button
          block="Button"
          mods={{ likeLink: true }}
          onClick={() => changeStore(store)}
        >
          {__("Show on the map")}
        </button>
      </div>
    );
  }
}

Solution

  • I made this functional component that has a working example with ScrollIntoView(). If I understood you right, you want to add the scrollIntoView()-function to an element. This is how you do it with functional components:

    import React, { useEffect, useRef } from 'react'
    
    export const TestComponent = () => {
      const inputEl = useRef(null) //"inputEl" is the element that you add the scroll function to
    
      useEffect(() => {
        inputEl.current.scrollIntoView() //use this if you want the scroll to happen when loading the page
      }, [inputEl])
    
      const onButtonClick = () => {
        inputEl.current.scrollIntoView() //use this if you want the scroll to happen on click instead.
      }
      return (
        <>
          <input ref={inputEl} type="text" />
          <button onClick={onButtonClick}>Focus the input</button>
        </>
      )
    }