Explain Codes LogoExplain Codes Logo

How to scroll to an element?

javascript
react
scrolling
smooth-scrolling
Alex KataevbyAlex Kataev·Sep 3, 2024
TLDR

Instantly scroll to an element with scrollIntoView:

document.querySelector('.target').scrollIntoView();

For smooth scrolling, adjust the options:

document.querySelector('.target').scrollIntoView({ behavior: 'smooth' });

React: instant teleportation tool

In the magical land of React, we use something called refs to access the DOM. It's like the Harry Potter Apparition spell, but for HTML elements:

const elementRef = useRef(null); // Think 'Accio Element!'

Wait... magic doesn't exist? Ok, let's bind this ref to our target, like a balloon to a mailbox:

<div ref={elementRef}>Target (not a mailbox, but bear with me)</div>

And now, we can scroll to our target just like the owl delivers letters at Hogwarts:

// Similar to 'Wingardium Leviosa', just less cool elementRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });

Remember to check the ref by using ?. to avoid the sad undefined error.

Cracking the scroll code

I know what you're thinking, "I just want the scroll, not the entire Marvel Universe". So, here we centralize and simplify this into a dedicated function:

const executeScroll = () => elementRef.current?.scrollIntoView( { behavior: 'smooth' } ); // Now, it's an Avenger!

Remember, avoid ReactDOM.findDOMNode - it's like inviting Thanos to the party.

Enable smooth scrolling through css written by magic markers:

html{ scroll-behavior: smooth; // Like greasing a slide }

For dynamic lists, like chatbot answering all the questions you have ever had at 2 AM

// Smart ref array. Those chatbots are getting too smart... const messagesEndRef = useRef([]); // Mapping msgs - a fancy way to say 'for each msg...' {messages.map((message, index) => ( // Add ref prop to each child <div key={index} ref={el => messagesEndRef.current[index] = el}>{message}</div> ))}

Scroll to the newest message:

// If it's new, scroll to it if (isNewMessage) { messagesEndRef.current[messages.length -1]?.scrollIntoView({ behavior: 'smooth' }); }

Mastering the scroll

Dynamic jumps

Need to jump between different elements? Add some dynamic logic to decide which element to scrollIntoView.

Scroll on cue

Implement cue-based scrolling. Scroll only when the user performs an action or an event happens.

Hide the complexity

Abstract the scrolling logic into functions or custom hooks. Focus on what matters and let abstraction handle the mechanics.