I have a chat widget that pulls up an array of messages every time I scroll up. The problem I am facing now is the slider stays fixed at the top when messages load. I want it to focus on the last index element from the previous array. I figured out that I can make dynamic refs by passing index, but I would also need to know what kind of scroll function to use to achieve that
handleScrollToElement(event) { const tesNode = ReactDOM.findDOMNode(this.refs.test) if (some_logic){ //scroll to testNode } } render() { return ( <div> <div ref="test"></div> </div>) }
The scrollTo method: The scrollTo() is used to scroll to the specified element in the browser. Syntax: Here, x-cord specifies the x-coordinate and y-cord specifies the y-coordinate. Example: Using scrollTo() to scroll to an element.
The scrollIntoView() method scrolls an element into the visible area of the browser window.
scrollTop = posArray[1]; Again, this will scroll the div so that the element you wish to see is exactly at the top (or if that's not possible, scrolled as far down as it can so it's visible).
const ScrollDemo = () => { const myRef = useRef(null) const executeScroll = () => myRef.current.scrollIntoView() // run this function from an event handler or an effect to execute scroll return ( <> <div ref={myRef}>Element to scroll to</div> <button onClick={executeScroll}> Click to scroll </button> </> ) }
Click here for a full demo on StackBlits
class ReadyToScroll extends Component { constructor(props) { super(props) this.myRef = React.createRef() } render() { return <div ref={this.myRef}>Element to scroll to</div> } executeScroll = () => this.myRef.current.scrollIntoView() // run this method to execute scrolling. }
class ReadyToScroll extends Component { render() { return <div ref={ (ref) => this.myRef=ref }>Element to scroll to</div> } executeScroll = () => this.myRef.scrollIntoView() // run this method to execute scrolling. }
String refs harm performance, aren't composable, and are on their way out (Aug 2018).
string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. [Official React documentation]
resource1resource2
/* css */ html { scroll-behavior: smooth; }
We want the ref to be attached to a dom element, not to a react component. So when passing it to a child component we can't name the prop ref.
const MyComponent = () => { const myRef = useRef(null) return <ChildComp refProp={myRef}></ChildComp> }
Then attach the ref prop to a dom element.
const ChildComp = (props) => { return <div ref={props.refProp} /> }
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