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.
React 16.3 +, Class component myRef}>Element to scroll to</div> } executeScroll = () => this. myRef. current. scrollIntoView() // run this method to execute scrolling. }
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.
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.
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.
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);
}
}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With