Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scrollIntoView using React refs

We are trying to scroll to a specific component when the user closes another component.

Our example is very similar to that down below, taken from https://reactjs.org/docs/refs-and-the-dom.html#exposing-dom-refs-to-parent-components

function CustomComponents(props) {
  const items = [1,2,3,4].map((x, i) => return (
    <div ref={props.inputRef} key={i}>
     x + hello
    </div>
  )

  return (
    <div>
      { items }
    </div>
  );
}

function Parent(props) {
  return (
    <div>
      <CustomComponents inputRef={props.inputRef} />
    </div>
  );
}


class Grandparent extends React.Component {
  render() {
    return (
      <Parent
        inputRef={el => this.inputElement = el}
      />
    );
  }
}

We are rendering a big list of cards and want to be able to scroll to a specific card by calling this.refs[elem].scrollIntoView()

But our problem is that calling this.refs returns an empty object at all levels, and so we are unable to attach to a specific element and then fire it when the user arrives back to view this component.

Would like some help on how one would go about solving this issue.

like image 617
Sohil Pandya Avatar asked Dec 13 '17 17:12

Sohil Pandya


People also ask

How do you scroll to element using REF IN React?

React 16.3 +, Class component myRef}>Element to scroll to</div> } executeScroll = () => this. myRef. current. scrollIntoView() // run this method to execute scrolling. }

What is scrollIntoView in React?

scrollIntoView() The Element interface's scrollIntoView() method scrolls the element's ancestor containers such that the element on which scrollIntoView() is called is visible to the user.

What is the difference between useRef and createRef?

useRef: The useRef is a hook that uses the same ref throughout. It saves its value between re-renders in a functional component and doesn't create a new instance of the ref for every re-render. It persists the existing ref between re-renders. createRef: The createRef is a function that creates a new ref every time.

How do you scroll to the top in React?

Use the window. scrollTo() method to scroll to the top of the page in React, e.g. window. scrollTo(0, 0) . The scrollTo method on the window object scrolls to a particular set of coordinates in the document.


Video Answer


1 Answers

I've solved my specific issue by providing an if statement written below in my Grandparent component.

inputRef={el => { 
  if (el && el.id == this.state.selectedBuildingRef) {
    this.myelement.scrollIntoView();
    window.scrollBy(0, -65);
  } 
}}
like image 179
Sohil Pandya Avatar answered Oct 05 '22 22:10

Sohil Pandya