Tari Ibaba

Tari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.

How to get the current route/URL in React Router

To get the current route in React Router, we use the useLocation() route.

For example:

JavaScript
import React from 'react'; import { Route, Link, Routes, useLocation } from 'react-router-dom'; function Home() { return <h2>Home</h2>; } function Products() { return <h2>About</h2>; } function Pricing() { return <h2>Pricing</h2>; } function Posts() { return <h2>Posts</h2>; } export default function App() { const location = useLocation(); const { hash, pathname, search } = location; return ( <div> <div> <Routes> <Route path="/products" element={<Products />} /> <Route path="/" element={<Home />} /> <Route path="/posts" element={<Posts />} /> <Route path="/#pricing" element={<Pricing />} /> </Routes> Pathname: <b>{pathname}</b><br /> Search params: <b>{search}</b><br /> Hash: <b>{hash}</b> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/products">Products</Link> </li> <li> <Link to="/posts?id=5">Posts</Link> </li> <li> <Link to="/#pricing">Pricing</Link> </li> </ul> </nav> </div> </div> ); }

useLocation() returns an object that contains information on the current page URL. Some of these properties are:

  • pathname: the part that comes after the domain name, e.g., /products.
  • search: the query string, e.g., ?id=5.
  • hash: the hash, e.g., #pricing.

Note

To get the full URL, we use location.href instead of useLocation().

JavaScript
const url = window.location.href;

Get current page URL in React

We you want to get the current page URL in React, you can use window.location.href.

For example:

JavaScript
import { useRef } from 'react'; export default function App() { const url = window.location.href; return ( <div> You are currently accessing url</b> </div> ); }
Displaying the current URL in React.

The window.location.href property returns a string that contains the entire page URL.

window.location contains other properties that give more information on the URL. Some of them are:

  • pathname: the path of the URL after the domain name and any optional port number.
  • protocol: the protocol scheme of the URL.
  • hostname: the hostname portion of the URL.

Here are some examples of using these properties to get various URL properties in addition to the full URL.

JavaScript
export default function App() { const url = window.location.href; const pathname = window.location.pathname; const protocol = window.location.protocol; const hostname = window.location.hostname; return ( <div> You are currently accessing <b>{url}</b><br /> Pathname: <b>{pathname}</b><br /> Protocol: <b>{protocol}</b><br /> Hostname: <b>{hostname}</b> </div> ); }
Displaying various URL properties.

Get dynamic route variable in React Router

To access the variables of a dynamic route directly in React Router, we use the useParams() hook.

For example:

JavaScript
import React from 'react'; import { Route, Routes, useParams } from 'react-router-dom'; function Posts() { const { id } = useParams(); return <h2>Settings for post {id} </h2>; } export default function App() { return ( <div> <div> <Routes> <Route path="/posts/:id" element={<Posts />} /> </Routes> </div> </div> ); }
Displaying the dynamic route variable.
Displaying the dynamic route variable.

The id variable corresponds to its placeholder value in the /posts/:id path. So as you saw in the example, the path /posts/5 will result in the id having a value of 5.

Get current route in Next.js app

To get the current route in a Next.js React app, we use the useRouter() hook:

The object useRouter() returns has an asPath property that is the current route in the Next.js app.

pages/posts.tsx
import Head from 'next/head'; import { useRouter } from 'next/router'; export default function Posts() { const posts = ['Post 1', 'Post 2', 'Post 3']; // 👇 Get route data const { route } = useRouter(); return ( <> <Head> <title>Next.js - Coding Beauty</title> <meta name="description" content="Generated by create next app" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> Route: <b>{router}</b> <br /> {posts.map((post) => ( <p>{post}</p> ))} </main> </> ); }

asPath returns the current route/path that’s rendering.

Including any query parameters or hash.

Displaying the current route in Next.js

We use useRouter() to get data and take actions related to the current app route.

Get current dynamic route data in Next.js

To get data passed to a dynamic route, we use the query property from the useRouter() object:

For instance, we could have a route /posts/5 corresponding to a dynamic route, /posts/:id where 5 is the passed value for id.

Here’s how we’ll access it in the Next.js file that handles requests to the dynamic route:

pages/posts/[id].tsx
import Head from 'next/head'; import { useRouter } from 'next/router'; export default function Posts() { const { query } = useRouter(); // 👇 Get id value from dynamic route const { id } = query; return ( <> <Head> <title>Next.js - Coding Beauty</title> <meta name="description" content="Generated by create next app" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> <h2> Post <b>{id}</b> </h2> </main> </> ); }
Displaying the data passed with the dynamic route in Next.js

For the dynamic route to work, the file structure in the pages folder has to be like this: /pages/[id].tsx. We name the file according to what property we’ll use to access the data from the query, and we wrap the name in square brackets.

We use useRouter() to get data and take actions related to the current app route.

Get query parameter data in Next.js

We can also access URL query parameters (i.e., ?key1=value1) using the query object:

pages/posts/[id].tsx
import Head from 'next/head'; import { useRouter } from 'next/router'; export default function Posts() { const { query } = useRouter(); // 👇 Get source from query params const { id, source } = query; return ( <> <Head> <title>Next.js - Coding Beauty</title> <meta name="description" content="Generated by create next app" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> <h2> Post <b>{id}</b> </h2> <h3>You came from {source}!</h3> </main> </> ); }
Display data passed with URL query parameters in Next.js

Key takeaways

  • In React Router, use the useLocation() hook to get the current route. It returns an object containing properties like pathname, search, and hash.
  • To get the full URL in a React app, use window.location.href.
  • In React Router, use the useParams() hook to access dynamic route variables.
  • In a Next.js app, use the useRouter() hook to get the current route and access dynamic route data.
  • The query property from the useRouter() object in Next.js allows you to access URL query parameters.

How to Scroll to the Top of a Page in Vue.js

To scroll to the top of a page in Vue.js, call window.scrollTo({ top: 0, left: 0}).

App.vue
<template> <div> <h2>Top of the page</h2> <div style="height: 100rem" /> <div ref="listOfCities"> <h2 v-for="city in allCities" :key="city">{{city}}</h2> </div> <button @click="scrollToTop">Scroll to top</button> <div style="height: 150rem" /> </div> </template> <script> export default { data() { return { allCities: [ 'Tokyo', 'New York City', 'Paris', 'London', 'Dubai', 'Sydney', 'Rio de Janeiro', 'Cairo', 'Singapore', 'Mumbai', ], }; }, methods: { scrollToTop() { window.scrollTo({ top: 0, left: 0, behavior: 'smooth' }); }, }, }; </script>
Clicking the button to scroll to the top of the page in Vue.js

The window.scrollTo() method scrolls to a particular position on a page.

We could have called it with two arguments: window.scrollTo(0, 0).

But this overload of scrollTo() doesn’t let us set a smooth scroll behavior.

When behavior is smooth, the browser scrolls to the top of the page in a gradual animation.

But when it’s auto, the scroll happens instantly. We immediately jump to the top of the page.

We use the @click directive of the button to set a click listener.

This listener will get called when the user clicks the button.

Scroll to bottom of page in Vue.js

We use a different approach to scroll to the end of the page in Vue.js.

We create an element at the end of the page.

We set a ref on it.

Then we scroll to it by calling scrollIntoView() on the ref.

App.vue
<template> <div> <h2>Top of the page</h2> <button @click="scrollToBottom">Scroll to bottom</button> <div style="height: 100rem" /> <div> <h2 v-for="city in allCities" :key="city">{{city}}</h2> </div> <div style="height: 150rem" /> <div ref="bottomElement"></div> <h2>Bottom of the page</h2> </div> </template> <script> export default { data() { return { allCities: [ 'Tokyo', 'New York City', 'Paris', 'London', 'Dubai', 'Sydney', 'Rio de Janeiro', 'Cairo', 'Singapore', 'Mumbai', ], }; }, methods: { scrollToBottom() { this.$refs.bottomElement.scrollIntoView({ behavior: 'smooth' }); }, }, }; </script>
Clicking the button to scroll to the bottom of the page in Vue.js

scrollIntoView() scrolls to a specific element on the page.

By calling it on the bottom element, we scroll to the page end.

Like scrollTo(), scrollIntoView() has a behavior option that controls the scrolling motion.

App.vue
scrollToBottom() { this.$refs.bottomElement?.scrollIntoView({ behavior: 'smooth' }); }

smooth scrolls to the element in an animation.

auto jumps to the element on the page instantly. It’s the default.

To access the bottom element, we set a Vue ref on it.

To do this, we create a ref object and set the element’s ref prop to it.

App.vue
<template> <div ref="bottomElement"></div> </template>

Doing this lets us access the element’s HTMLElement object with this.$refs.bottomElement.

Vue refs are a way to register a reference to an element or a child component.

The registered reference will be updated whenever the component re-renders.

Key takeaways

  • In Vue.js, to scroll to the top of a page, call window.scrollTo() with { top: 0, left: 0, behavior: 'smooth' }.
  • Setting behavior to 'smooth' makes a gradual animated scroll to the top.
    'auto' causes an instant jump to the top.
  • To scroll to the bottom of a page in Vue.js, call scrollIntoView() on a specific element.
    Create a ref for it using the ref attribute first.
  • Vue refs are used to create a reference to an element.
    This allows access to its properties during the component’s lifecycle.

How to Convert Array Values to Object Keys in JavaScript

To convert array values to object keys in JavaScript:

  1. Loop through the array with reduce().
  2. For each array item, create a keyed object item.

reduce() will return an object with keys.

Each value for each key is an array item.

JavaScript
const arr = ['animal', 'color', 'food']; const obj = arr.reduce((accumulator, value) => { return {...accumulator, [value]: ''}; }, {}); console.log(obj); // {animal: '', color: '', food: ''}

We use the reduce method to combine all the array elements into a single value.

In this example, it takes an array of words and creates an object.

It starts with an empty object {} as the initial value.

Then, for each word in the array, it adds a new property to the object.

The property key is the word and the value is the empty string.

Finally, it returns the resulting object.

So, the output will be an object with properties for each word in the array, where the values are empty strings.

Let’s look at a more realistic example:

JavaScript
const tasks = [ { title: 'animal', date: '2023-05-20', complete: false, }, { title: 'color', date: '2023-05-21', complete: false, }, { title: 'food', date: '2023-05-22', complete: true, }, ]; const completed = tasks.filter((task) => task.complete); const obj = completed.reduce((accumulator, task) => { return { ...accumulator, [task.title]: task }; }, {}); // { food: { title: 'food', date: '2023-05-22', complete: true } } console.log(obj);

Trying to convert an array of objects where each item has an id property.

Consider a sample todo-list app.

The state is modeled as an object of key-value pairs.

Each key is an ID. The value is the task object with that ID.

Let’s say we just filtered out a list of tasks to get the completed items.

Then we want to convert it back to objects keyed by an id.

JavaScript
const obj = completed.reduce((accumulator, task) => { return { ...accumulator, [task.title]: task }; }, {});

Convert array values to object keys with for..of

We can also use a for..of loop to quickly convert array values to object keys:

JavaScript
const arr = ['animal', 'color', 'food']; const obj = {}; for (const value of arr) { obj[value] = ''; } console.log(obj); // {animal: '', color: '', food: ''}

This is a more imperative approach, showing how it’s done step-by-step.

for..of loops through iterable objects like arrays, strings, Maps, NodeList, and Set objects, and generators.

What we do here is basically what reduce() does. We loop through an array and accumulate a value using each array element.

Of course, this for..of also works for an array of objects:

JavaScript
const tasks = [ { title: 'animal', date: '2023-05-20', complete: false, }, { title: 'color', date: '2023-05-21', complete: false, }, { title: 'food', date: '2023-05-22', complete: true, }, ]; const completed = tasks.filter((task) => task.complete); const obj = {}; for (const task of completed) { obj[task.title] = task; } // { food: { title: 'food', date: '2023-05-22', complete: true } } console.log(obj);

Convert array values to object keys with forEach()

Anywhere we use for..of, we can also forEach().

So here’s another way to convert an object array to object keys:

JavaScript
const arr = ['animal', 'color', 'food']; const obj = {}; arr.forEach(value => { obj[value] = ''; }); console.log(obj); // {animal: '', color: '', food: ''}

forEach() takes a callback and calls it on every item in an array.

Key takeaways

  1. To convert array values to object keys in JavaScript, you can use the reduce() method.
    With reduce(), you can create a keyed object item for each array item.
    This results in an object with keys.
    Each value for each key is an array item.
  2. Alternatively, you can use a for..of loop to convert array values to object keys.
  3. The forEach() loop can also be used to convert an array to an object with keys.

How to Scroll to the Top of a Page in React

To scroll to the top of a page in React, call window.scrollTo({ top: 0, left: 0}).

JavaScript
import { useRef } from 'react'; const allCities = [ 'Tokyo', 'New York City', 'Paris', 'London', 'Dubai', 'Sydney', 'Rio de Janeiro', 'Cairo', 'Singapore', 'Mumbai', ]; export default function App() { const ref = useRef(null); const scrollToTop = () => { window.scrollTo({ top: 0, left: 0, behavior: 'smooth' }); }; return ( <div> <h2>Top of the page</h2> <div style={{ height: '100rem' }} /> <div ref={ref}> {allCities.map((fruit) => ( <h2 key={fruit}>{fruit}</h2> ))} </div> <button onClick={scrollToTop}>Scroll to top</button> <div style={{ height: '150rem' }} /> </div> ); }
Clicking the button to scroll to the top of the page in React.

The window.scrollTo() method scrolls to a particular position in a page.

JavaScript
const scrollToTop = () => { window.scrollTo({ top: 0, left: 0, behavior: 'smooth' }); };

We could have called it with two arguments: window.scrollTo(0, 0).

But this overload doesn’t let us set a smooth scroll behavior.

When behavior is smooth, the browser scrolls to the top of the page in a gradual animation.

But when it’s auto, the scroll happens instantly. We immediately jump to the top of the page.

We use the onClick prop of the button to set a click listener.

This listener will get called when the user clicks the button.

Scroll to bottom of page in React

To scroll to the end of the page in React, we use a different approach.

We create an element at the end of the page.

We set a ref on it.

Then we scroll to it by calling scrollIntoView() on the ref.

JavaScript
import { useRef } from 'react'; const allCities = [ 'Tokyo', 'New York City', 'Paris', 'London', 'Dubai', 'Sydney', 'Rio de Janeiro', 'Cairo', 'Singapore', 'Mumbai', ]; export default function App() { const bottomRef = useRef(null); const scrollToBottom = () => { bottomRef.current.scrollIntoView({ behavior: 'smooth' }); }; return ( <div> <h2>Top of the page</h2> <button onClick={scrollToBottom}>Scroll to bottom</button> <div style={{ height: '100rem' }} /> <div> {allCities.map((fruit) => ( <h2 key={fruit}>{fruit}</h2> ))} </div> <div style={{ height: '150rem' }} /> <div ref={bottomRef}></div> <h2>Bottom of the page</h2> </div> ); }
Clicking the button to scroll to the bottom of the page in React.

scrollIntoView() scrolls to a certain element on the page.

By calling it on the bottom element, we scroll to the page end.

Like scrollTo(), scrollIntoView() has a behavior option that controls the scrolling motion.

JavaScript
const scrollToBottom = () => { bottomEl?.current?.scrollIntoView({ behavior: 'smooth' }); };

smooth scrolls to the element in an animation.

auto jumps to the element on the page instantly. It’s the default.

To access the bottom element, we set a React ref on it.

We create a ref object with the useRef hook and set the element’s ref prop to it.

JavaScript
const bottomEl = useRef(null);

Doing this sets the ref object’s current property to the element’s HTMLElement object.

useRef returns a mutable object that maintains its value when a component updates.

Also, modifying the value of this object’s current property doesn’t cause a re-render.

This is unlike the setState update function return from the useState hook.

Key takeaways

  • In React, to scroll to the top of a page, call window.scrollTo() with { top: 0, left: 0, behavior: 'smooth' }.
  • Setting the behavior property to 'smooth' provides a gradual animated scroll to the top, while 'auto' causes an instant jump to the top.
  • To scroll to the bottom of a page in React, call scrollIntoView() on a specific element by creating a ref for it using the useRef hook.
  • By setting the behavior property to 'smooth', the browser will smoothly scroll to the referenced element at the bottom of the page.
  • useRef is used to create a mutable reference to an element, allowing access to its properties without causing a re-render.

How to Scroll to the Bottom of a div Element in Vue.js

To scroll to the bottom of a div element in Vue.js:

  1. Create an element at the bottom of the div.
  2. Set a ref on this element.
  3. Call scrollIntoView() on the ref to scroll down to this element.
Vue
<template> <div> <div style=" position: fixed; background-color: white; bottom: 0; margin-bottom: 10px; " > <button @click="scrollToBottom" style="margin-left: 8px" > Scroll to bottom </button> </div> <div style="height: 5rem"></div> <div> <h2 v-for="fruit in allFruits" :key="fruit" > {{ fruit }} </h2> <!-- 👇 Element created at the bottom --> <div ref="bottomEl"></div> </div> <div style="height: 150rem"></div> </div> </template> <script> export default { data() { return { allFruits: [ 'Apples', 'Bananas', 'Oranges', 'Grapes', 'Strawberries', 'Blueberries', 'Pineapples', 'Mangoes', 'Kiwis', 'Watermelons', ], }; }, methods: { scrollToBottom() { this.$refs.bottomEl?.scrollIntoView({ behavior: 'smooth' }); }, }, }; </script>
Clicking the button to the bottom of the div in Vue.js

Here we have a list of fruits displayed.

The Scroll to bottom button scrolls to the bottom of the div on click.

It does this by calling scrollIntoView() in a click event listener we set on the bottom element’s ref.

Vue
... <script> ... methods: { scrollToBottom() { this.$refs.bottomEl?.scrollIntoView({ behavior: 'smooth' }); }, }, }; </script>

We set the behavior option to smooth to make the element scroll into view in an animated way, instead of jumping straight to the element in the next frame – auto.

auto is the default.

We create the Vue ref using the div element’s ref prop.

Vue
<template> <div> ... <div> ... <div ref="bottomEl"></div> </div> </div> </template> ...

Doing lets us access the HTMLElement representing the div using this.$refs.bottomEl.

Scroll to bottom of dynamic list div in Vue.js

We can do something similar to scroll to the bottom of a div containing a list of items that change over time.

Vue
<template> <div> <div style=" position: fixed; background-color: white; bottom: 0; margin-bottom: 10px; " > <button @click="addFruit">Add fruit</button> <button @click="scrollToLastFruit" style="margin-left: 8px" > Scroll to last </button> </div> <div style="height: 5rem"></div> <div ref="fruitsContainer"> <h2 v-for="fruit in fruits" :key="fruit" > {{ fruit }} </h2> </div> <div style="height: 150rem"></div> </div> </template> <script> export default { data() { return { allFruits: [ 'Apples', 'Bananas', 'Oranges', 'Grapes', 'Strawberries', 'Blueberries', 'Pineapples', 'Mangoes', 'Kiwis', 'Watermelons', ], fruits: [], }; }, mounted() { this.fruits = [...this.allFruits.slice(0, 3)]; }, methods: { addFruit() { this.fruits.push(this.allFruits[this.fruits.length]); }, scrollToLastFruit() { const lastChildElement = this.$refs.fruitsContainer.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth', }); }, }, }; </script>
Scrolling to a bottom of a dynamic list div in Vue.js.

Like in the previous example, we also have a list of fruits displayed here.

But this time the list isn’t static – when can add an item to it with the Add fruit button.

The Scroll to last button scrolls to the last item in the div – the most recently added item.

Like before, we use the click event to set a click event listener on the button.

We set the ref on the list instead of a list item, since the items are created dynamically, and the last item will not always be the same.

Vue
<template> <div> <div ... > ... <div ref="fruitsContainer"> ... </div> ... </div> </template>

Doing this lets us access the HTML element using this.$refs.

In this listener, we use the lastElementChild property of the list element to get its last item element. Then we call scrollIntoView() on this last item to scroll down to it.

Vue
... <script> export default { ... methods: { scrollToLastFruit() { const lastChildElement = this.$refs.fruitsContainer.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth', }); }, }, }; </script>

Scroll to bottom of div after render

Sometimes we want to scroll to the bottom of the div immediately after the page renders.

If we want to scroll to the bottom of the list in the previous section,

we’ll just call scrollIntoView() from the mounted hook:

Vue
... <script> export default { ... mounted() { this.scrollToLastFruit(); }, methods: { scrollToLastFruit() { const lastChildElement = this.$refs.fruitsContainer.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth', }); }, }, }; </script>
Scrolling to the bottom of a div list after render in Vue.js

The code in the mounted hook is run just after the component mounts.

So we call scrollToLastFruit() here, which in turn calls scrollIntoView() to scroll to the bottom of the list div.

Here’s the full code for reference:

Vue
<template> <div> <div style="height: 5rem"></div> <div ref="fruitsContainer"> <h2 v-for="fruit in allFruits" :key="fruit" > {{ fruit }} </h2> </div> <div style="height: 150rem"></div> </div> </template> <script> export default { data() { return { allFruits: [ 'Apples', 'Bananas', 'Oranges', 'Grapes', 'Strawberries', 'Blueberries', 'Pineapples', 'Mangoes', 'Kiwis', 'Watermelons', ], }; }, mounted() { this.scrollToLastFruit(); }, methods: { scrollToLastFruit() { const lastChildElement = this.$refs.fruitsContainer.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth', }); }, }, }; </script>

We removed the buttons to focus on the scroll after render.

Key takeaways:

  1. To scroll to the bottom of a div element in Vue.js, create a bottom element and set a ref on it.
    Then use the scrollIntoView() method on the ref to scroll down to the bottom element.
  2. Set the behavior option to 'smooth' for animated scrolling.
  3. For dynamically changing lists, set the ref on the container element and use lastElementChild to scroll to the last item.
  4. Use the mounted hook to scroll to the bottom immediately after rendering.

How to Scroll to the Bottom of a Div Element in React

To scroll to the bottom of a div element in React:

  1. Create an element at the bottom of the div.
  2. Set a ref on this element.
  3. Call scrollIntoView() on the ref to scroll down to this element.
JavaScript
import { useRef } from 'react'; const allFruits = [ 'Apples', 'Bananas', 'Oranges', 'Grapes', 'Strawberries', 'Blueberries', 'Pineapples', 'Mangoes', 'Kiwis', 'Watermelons', ]; export default function App() { const bottomEl = useRef(null); const scrollToBottom = () => { bottomEl?.current?.scrollIntoView({ behavior: 'smooth' }); }; return ( <div> <div style={{ position: 'fixed', backgroundColor: 'white', bottom: 0, marginBottom: 10, }} > <button onClick={scrollToBottom} style={{ marginLeft: '8px' }}> Scroll to bottom </button> </div> <div style={{ height: '5rem' }} /> <div> {allFruits.map((fruit) => ( <h2 key={fruit}>{fruit}</h2> ))} {/* 👇 Element created at the bottom */} <div ref={bottomEl}></div> </div> <div style={{ height: '150rem' }} /> </div> ); }
Clicking the button to scroll to the bottom of the div in React.

Here we have a list of fruits displayed.

The Scroll to bottom button scrolls to the bottom of the div on click.

It does this by calling scrollIntoView() in a click event listener we set, on the bottom element’s ref.

JavaScript
const scrollToBottom = () => { bottomEl?.current?.scrollIntoView({ behavior: 'smooth' }); };

We set the behavior option to smooth to make the element scroll into view in an animated way, instead of jumping straight to the element in the next frame – auto.

auto is the default.

We create the ref object with the useRef hook and assign it to the ref prop of the target div element.

JavaScript
const bottomEl = useRef(null);

Doing this sets the current property of the ref object to the DOM object that represents the element.

useRef returns a mutable object that maintains its value when a component updates.

Also, modifying the value of this object’s current property doesn’t cause a re-render.

This is unlike the setState update function return from the useState hook.

Scroll to bottom of dynamic list div in React

We can do something similar to scroll to the bottom of a div containing a list of items that change.

JavaScript
import { useRef, useState } from 'react'; const allFruits = [ 'Apples', 'Bananas', 'Oranges', 'Grapes', 'Strawberries', 'Blueberries', 'Pineapples', 'Mangoes', 'Kiwis', 'Watermelons', ]; export default function App() { const ref = useRef(null); const [fruits, setFruits] = useState([...allFruits.slice(0, 3)]); const addFruit = () => { setFruits((prevFruits) => [...prevFruits, allFruits[prevFruits.length]]); }; const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); }; return ( <div> <div style={{ position: 'fixed', backgroundColor: 'white', bottom: 0, marginBottom: 10, }} > <button onClick={addFruit}>Add fruit</button> <button onClick={scrollToLastFruit} style={{ marginLeft: '8px' }}> Scroll to last </button> </div> <div style={{ height: '5rem' }} /> <div ref={ref}> {fruits.map((fruit) => ( <h2 key={fruit}>{fruit}</h2> ))} </div> <div style={{ height: '150rem' }} /> </div> ); }
Scrolling to a dynamic element in a list div in React.

Like in the previous example, we also have a list of fruits displayed here.

But this time the list isn’t static – when can add an item to it with the Add fruit button.

The Scroll to last button scrolls to the last item in the div – the most recently added item.

Like before, we use the onClick prop to set a click event listener on the button.

We set the ref on the list instead of a list item, since the items are created dynamically, and the last item will not always be the same.

Doing this sets the current property of the ref object to the DOM object that represents the list element.

In this listener, we use the lastElementChild property of the list element to get its last item element. Then we call scrollIntoView() on this last item to scroll down to it.

JavaScript
const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); };

Scroll to bottom of div after render

Sometimes we want to scroll to the bottom of the div immediately after the page renders.

Like if we want to scroll to the bottom of the list in the previous section,

we’ll just a useEffect() hook and call scrollIntoView() in the hook.

JavaScript
const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); }; useEffect(() => { scrollToLastFruit(); }, []); // 👈 empty deps array
Scrolling to the bottom of a div list after render in React.

The code in useEffect is run after the component mounts.

And also when any value in the dependency array changes.

We pass an empty dependency array – so there are no dependencies.

So the useEffect will only run when the component mounts.

Here’s the full code for reference:

JavaScript
import { useEffect, useRef } from 'react'; const allFruits = [ 'Apples', 'Bananas', 'Oranges', 'Grapes', 'Strawberries', 'Blueberries', 'Pineapples', 'Mangoes', 'Kiwis', 'Watermelons', ]; export default function App() { const ref = useRef(null); const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); }; useEffect(() => { scrollToLastFruit(); }, []); // 👈 empty deps array return ( <div> <div style={{ height: '5rem' }} /> <div ref={ref}> {allFruits.map((fruit) => ( <h2 key={fruit}>{fruit}</h2> ))} </div> <div style={{ height: '150rem' }} /> </div> ); }

Key takeaways

  1. To scroll to the bottom of a div element in React, create a ref on the target element and use scrollIntoView().
  2. The useRef hook creates a mutable ref object that can be assigned to the ref prop.
  3. Set the behavior option to smooth for a smooth scrolling animation.
  4. For dynamic lists, set the ref on the container element and scroll to the last child element.
  5. To scroll to the bottom immediately after rendering, use useEffect with an empty dependency array.
  6. The code within useEffect runs after mounting and when dependency values change.

How to to Scroll to an Element in Vue.js

To scroll to an element in Vue.js:

  1. Set a ref on the target element.
  2. Call scrollIntoView() on the target ref.
HTML
// Set ref on target element <div ref="targetRef" style="background-color: lightblue;"> My Target Element </div>
JavaScript
// Scroll to element this.$refs.targetRef.scrollIntoView({ behavior: 'smooth' });

We can use this approach to scroll to an element when another trigger element is clicked.

We’ll first need to set a click event listener on the trigger element.

Then we’ll call scrollIntoView() in the listener.

App.vue
<template> <div id="app"> <button @click="handleClick">Scroll to element</button> <div style="height: 150rem;"></div> <div ref="targetRef" style="background-color: lightblue;"> Coding Beauty </div> <div style="height: 150rem;"></div> </div> </template> <script> export default { data() { return { ref: null }; }, methods: { handleClick() { this.$refs.targetRef.scrollIntoView({ behavior: 'smooth' }); } } }; </script>
Using the button to scroll down to an element in Vue.js.

Scrolling on click is great for quick navigation.

It improves the user experience.

It’s great for long lists and pages with many sections.

It makes apps more interactive with smooth-scrolling animations.

We set the ref prop of the target element to create a Vue ref.

Doing this lets us access the component’s HTML element directly from the $refs instance property.

We use the @click event to set an event listener that will be called when the trigger element is clicked.

App.vue
<button @click="handleClick">Scroll to element</button>
App.vue
methods: { handleClick() { this.$refs.targetRef.scrollIntoView({ behavior: 'smooth' }); } }

We can use this same combo of refs and scrollIntoView() to scroll to an element in React.

In the click listener, we call the scrollIntoView() method on the ref of the target div element to scroll down to it and display it to the user.

We set the behavior option to smooth to make the element scroll into view in an animated way, instead of jumping straight to the element in the next frame – auto.

auto is the default.

Scroll to dynamic element on click in Vue.js

We can do something similar to scroll to a dynamically created element in Vue.js:

App.vue
<template> <div id="app"> <div style=" position: fixed; background-color: white; bottom: 0; margin-bottom: 10px; " > <button @click="addFruit">Add fruit</button> <button @click="scrollToLastFruit" style="margin-left: 8px" > Scroll to last </button> </div> <div style="height: 5rem"></div> <div ref="fruitList"> <h2 v-for="fruit in fruits" :key="fruit" > {{ fruit }} </h2> </div> <div style="height: 150rem"></div> </div> </template> <script> const allFruits = [ 'Apples', 'Bananas', 'Oranges', 'Grapes', 'Strawberries', 'Blueberries', 'Pineapples', 'Mangoes', 'Kiwis', 'Watermelons', ]; export default { data() { return { fruits: allFruits.slice(0, 3), }; }, methods: { addFruit() { this.fruits.push(allFruits[this.fruits.length]); }, scrollToLastFruit() { const lastChildElement = this.$refs.fruitList.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth', }); }, }, }; </script>
Scrolling to a dynamic element in Vue.js.

Here we have a list of fruits displayed.

The Add fruit button dynamically adds an item to the fruit list on click.

Then the Scroll to last button scrolls to this item on click, as it’s the last in the list.

Like before, we use the @click event to set a click event listener on the button.

This time we set the ref on the list instead of the items since the items are created dynamically, and the last item will not be constant.

Doing this sets the Vue instance’s $refs.inputList property to the DOM object that represents the list element.

In this listener, we use the lastElementChild property of the list element to get its last item element. Then we call scrollIntoView() on this last item to scroll down to it.

App.vue
methods: { addFruit() { this.fruits.push(allFruits[this.fruits.length]); }, scrollToLastFruit() { const lastChildElement = this.$refs.fruitList.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth', }); }, },

Scroll to element after render in Vue.js

To scroll to an element after render in Vue.js:

  1. Set a ref on the element
  2. Create a mounted lifecycle hook to run code just after the component mounts.
  3. Call scrollIntoView() on the ref object in the mounted hook.
App.vue
<template> <div> <div style="height: 150rem"></div> <div ref="target" style="background-color: blue; color: white" > Coding Beauty </div> <div style="height: 150rem"></div> </div> </template> <script> export default { mounted() { this.scrollToElement(); }, methods: { scrollToElement() { this.$refs.target.scrollIntoView({ behavior: 'smooth', }); }, }, }; </script>
Scrolling to an element after render in Vue.js

Scrolling after page loads help users find info.

It also helps fix errors.

It’s great for those who use special software.

It makes browsing the webpage easier.

We create a Vue ref by setting the target element’s ref prop to a string ("target")

We’ll then be able to access the HTMLElement object representing this object from the $refs property of the Vue instance (this.$refs.target).

The mounted method is a Vue lifecycle hook that runs just after the component has mounted. This is similar to useEffect in React.

In mounted, we call the scrollIntoView() method on the ref of the target div element to scroll down to it and display it to the user.

We set the behavior option to smooth to make the element scroll into view in an animated way, instead of jumping straight to the element in the next frame (auto).

auto is the default.

Key takeaways

  • To scroll to an element in Vue, set a ref on the target element and call scrollIntoView() on the ref.
  • To scroll to a dynamically created element in Vue.js, set the ref on the list element and use lastElementChild to scroll to its last item.
  • To scroll to an element after render in Vue.js, create a mounted lifecycle hook and call scrollIntoView() on the ref object in the mounted hook.

How to Scroll to an Element in React

To scroll to an element in React, set a ref on the target element, then call scrollIntoView() on the target ref.

We can use this approach to scroll to an element when another trigger element is clicked.

We’ll first need to set a click event listener on the trigger element.

Then we’ll call scrollIntoView() in the listener.

JavaScript
import { useRef } from 'react'; export default function App() { const ref = useRef(null); const handleClick = () => { ref.current?.scrollIntoView({ behavior: 'smooth' }); }; return ( <div> <button onClick={handleClick}>Scroll to element</button> <div style={{ height: '150rem' }} /> <div ref={ref} style={{ backgroundColor: 'lightblue' }}> Coding Beauty </div> <div style={{ height: '150rem' }} /> </div> ); }
Scrolling to an element on click in React

Scrolling on click is great for quick navigation.

It improves the user experience.

It’s great for long lists and pages with many sections.

It makes apps more interactive with smooth-scrolling animations.

We create a ref object with the useRef hook and assign it to the ref prop of the target div element.

Doing this sets the current property of the ref object to the DOM object that represents the element.

useRef returns a mutable object that maintains its value when a component updates.

Also, modifying the value of this object’s current property doesn’t cause a re-render.

This is unlike the setState update function return from the useState hook.

We use the onClick on the button to a click listener to it. So, this listener will be called when the user clicks the button.

JavaScript
const handleClick = () => { ref.current?.scrollIntoView({ behavior: 'smooth' }); };

In the handleClick listener, we call the scrollIntoView() method on the ref of the target div element to scroll down to it and display it to the user.

We set the behavior option to smooth to make the element scroll into view in an animated way, instead of jumping straight to the element in the next frame – auto.

auto is the default.

Scroll to dynamic element on click in React

We can do something similar to scroll to a dynamically created element in React:

JavaScript
import { useRef, useState } from 'react'; const allFruits = [ 'Apples', 'Bananas', 'Oranges', 'Grapes', 'Strawberries', 'Blueberries', 'Pineapples', 'Mangoes', 'Kiwis', 'Watermelons', ]; export default function App() { const ref = useRef(null); const [fruits, setFruits] = useState([...allFruits.slice(0, 3)]); const addFruit = () => { setFruits((prevFruits) => [...prevFruits, allFruits[prevFruits.length]]); }; const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); }; return ( <div> <div style={{ position: 'fixed', backgroundColor: 'white', bottom: 0, marginBottom: 10, }} > <button onClick={addFruit}>Add fruit</button> <button onClick={scrollToLastFruit} style={{ marginLeft: '8px' }}> Scroll to last </button> </div> <div style={{ height: '5rem' }} /> <div ref={ref}> {fruits.map((fruit) => ( <h2 key={fruit}>{fruit}</h2> ))} </div> <div style={{ height: '150rem' }} /> </div> ); }
Scrolling to a dynamic element on click in React.

Here we have a list of fruits displayed.

The Add fruit button dynamically adds an item to the fruit list on click.

Then the Scroll to last button scrolls to this item on click, as it’s the last in the list.

Like before, we use the onClick prop to set a click event listener on the button.

This time we set the ref on the list instead of the items since the items are created dynamically, and the last item will not be constant.

Doing this sets the current property of the ref object to the DOM object that represents the list element.

In this listener, we use the lastElementChild property of the list element to get its last item element. Then we call scrollIntoView() on this last item to scroll down to it.

JavaScript
const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); };

Scroll to element after render in React

To scroll to an element after render on React:

  1. Set a ref on the element.
  2. Create a useEffect hook to run code just after the component mounts.
  3. Call scrollIntoView() on the ref object in useEffect.
JavaScript
import { useEffect, useRef } from 'react'; export default function App() { const ref = useRef(null); const scrollToElement = () => { ref.current?.scrollIntoView({ behavior: 'smooth' }); }; useEffect(() => { scrollToElement(); }, []); return ( <div> <div style={{ height: '150rem' }} /> <div ref={ref} style={{ backgroundColor: 'blue', color: 'white' }}> Coding Beauty </div> <div style={{ height: '150rem' }} /> </div> ); }
Scrolling to a particular element after render in React.

Scrolling after page loads help users find info.

It also helps fix errors.

It’s great for those who use special software.

It aids web navigation.

Like before, we create a ref object with the useRef hook and assign it to the ref prop of the target div element.

Doing this sets the current property of the ref object to the DOM object that represents the element.

useRef returns a mutable object that maintains its value when a component updates.

Also, modifying the value of this object’s current property doesn’t cause a re-render.

This is unlike the setState update function return from the useState hooks.

The useEffect hook performs an action after the component renders, and when one or more of its dependencies change.

We passed an empty dependencies array ([]) to make sure that action only runs when the component mounts.

In useEffect, we call the scrollIntoView() method on the ref of the target div element to scroll down to it and display it to the user.

We set the behavior option to smooth to make the element scroll into view in an animated way, instead of jumping straight to the element in the next frame (auto).

auto is the default.

Key takeaways

In React, we can use refs to scroll to a specific element on the page.

We can set a click event listener on a trigger element and call scrollIntoView() on the target ref to scroll to the desired element.

useRef() returns a mutable object that maintains its value when a component updates, allowing us to reference DOM elements.

Setting a ref on a list container allows us to dynamically scroll to the last item in the list.

We can use useEffect() to scroll to an element after the component mounts, improving the user experience and aiding web navigation.

Setting the behavior option to smooth in scrollIntoView() produces a smooth scrolling animation instead of an abrupt jump to the element.

How to Scroll to an Element After Render in React

To scroll to an element after render on React:

  1. Set a ref on the element.
  2. Create a useEffect hook to run code just after the component mounts.
  3. Call scrollIntoView() on the ref object in useEffect.
JavaScript
import { useEffect, useRef } from 'react'; export default function App() { const ref = useRef(null); const scrollToElement = () => { ref.current?.scrollIntoView({ behavior: 'smooth' }); }; useEffect(() => { scrollToElement(); }, []); return ( <div> <div style={{ height: '150rem' }} /> <div ref={ref} style={{ backgroundColor: 'blue', color: 'white' }}> Coding Beauty </div> <div style={{ height: '150rem' }} /> </div> ); }
Scrolling to a particular element after render in React.

Scrolling to an element after the page loads in React helps users quickly find important information, fix errors, and is useful for those who use special software to navigate the web.

We create a ref object with the useRef hook and assign it to the ref prop of the target div element. Doing this sets the current property of the ref object to the DOM object that represents the element.

useRef returns a mutable object that maintains its value when a component updates. Also, modifying the value of this object’s current property doesn’t cause a re-render. This is unlike the setState update function return from the useState hooks.

The useEffect hook performs an action after the component renders, and when one or more of its dependencies change. We passed an empty dependencies array ([]) to make sure that action only runs when the component mounts.

In useEffect, we call the scrollIntoView() method on the ref of the target div element to scroll down to it and display it to the user.

We set the behaviour option to smooth to make the element scroll into view in an animated way, instead of jumping straight to the element in the next frame (auto). auto is the default.

Scroll to element on click in React

Learn more: How to Scroll to an Element on Click in React

We can do something similar to scroll to an element on click in React:

  1. Set a ref on the target element.
  2. Set a click listener on the element meant to cause the scroll.
  3. In the click event listener, call the scrollIntoView() method on the ref object.
JavaScript
import { useRef } from 'react'; export default function App() { const ref = useRef(null); const handleClick = () => { ref.current?.scrollIntoView({ behavior: 'smooth' }); }; return ( <div> <button onClick={handleClick}>Scroll to element</button> <div style={{ height: '150rem' }} /> <div ref={ref} style={{ backgroundColor: 'lightblue' }}> Coding Beauty </div> <div style={{ height: '150rem' }} /> </div> ); }
Scrolling to an element on click.

Scrolling to an element on click improves user experience by allowing for quick navigation, especially for long lists or pages with multiple sections. It can also add a touch of interactivity through smooth-scrolling animations.

We create a ref object with the useRef hook and assign it to the ref prop of the checkbox input. Doing this sets the current property of the ref object to the DOM object that represents the target element.

useRef returns a mutable object that retains its value when a component updates. Changing the value of this object’s current property doesn’t cause a re-render. This is different from the setState update function that useState returns.

We use the onClick on the button to a click listener to it. So, this listener will be called when the user clicks the button.

JavaScript
const handleClick = () => { ref.current?.scrollIntoView({ behavior: 'smooth' }); };

In the handleClick listener, we call the scrollIntoView() method on the ref of the target div element to scroll down to it and display it to the user.

As before, we set the behaviour option to smooth to make the element scroll into view in an animated way, instead of jumping straight to the element in the next frame – autoauto is the default.

Scroll to dynamic element on click in React

We can also scroll to a dynamically created element in React.

JavaScript
import { useRef, useState } from 'react'; const allFruits = [ 'Apples', 'Bananas', 'Oranges', 'Grapes', 'Strawberries', 'Blueberries', 'Pineapples', 'Mangoes', 'Kiwis', 'Watermelons', ]; export default function App() { const ref = useRef(null); const [fruits, setFruits] = useState([...allFruits.slice(0, 3)]); const addFruit = () => { setFruits((prevFruits) => [...prevFruits, allFruits[prevFruits.length]]); }; const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); }; return ( <div> <div style={{ position: 'fixed', backgroundColor: 'white', bottom: 0, marginBottom: 10, }} > <button onClick={addFruit}>Add fruit</button> <button onClick={scrollToLastFruit} style={{ marginLeft: '8px' }}> Scroll to last </button> </div> <div style={{ height: '5rem' }} /> <div ref={ref}> {fruits.map((fruit) => ( <h2 key={fruit}>{fruit}</h2> ))} </div> <div style={{ height: '150rem' }} /> </div> ); }
Scrolling to a dynamic element on click in React.

Here we have a list of fruits displayed. The Add fruit button dynamically adds an item to the fruit list on click. Then the Scroll to last button scrolls to this item on click, as it’s the last in the list.

Like before, we use the onClick prop to set a click event listener on the button.

This time we set the ref on the list instead of the items since the items are created dynamically, and the last item will not be constant. Doing this sets the current property of the ref object to the DOM object that represents the list element.

In this listener, we use the lastElementChild property of the list element to get its last item element. Then we call scrollIntoView() on this last item to scroll down to it.

JavaScript
const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); };

Key takeaways

  • To scroll to an element after render, set a ref on the element, then call scrollIntoView() on the ref object in useEffect.
  • To scroll to an element on click, set a click listener on the element and call scrollIntoView() on the ref object in the click event listener.
  • To scroll to a dynamic element on click, set the ref on the list, use lastElementChild to get the last item element and call scrollIntoView() on it.

How to Scroll to an Element on Click in React

To scroll to an element on click in React:

  1. Set a ref on the target element.
  2. Set a click listener on the element meant to cause the scroll on click.
  3. In the click event listener, call the scrollIntoView() method on the ref object.
App.jsx
import { useRef } from 'react'; export default function App() { const ref = useRef(null); const handleClick = () => { ref.current?.scrollIntoView({ behavior: 'smooth' }); }; return ( <div> <button onClick={handleClick}>Scroll to element</button> <div style={{ height: '150rem' }} /> <div ref={ref} style={{ backgroundColor: 'lightblue' }}> Coding Beauty </div> <div style={{ height: '150rem' }} /> </div> ); }
Scrolling to an element on click in React

Scrolling to an element on click improves user experience by allowing for quick navigation, especially for long lists or pages with multiple sections. It can also add a touch of interactivity to navigation through smooth-scrolling animations.

We create a ref object with the useRef hook and assign it to the ref prop of the target div element. Doing this sets the current property of the ref object to the DOM object that represents the element.

useRef returns a mutable object that maintains its value when a component updates. Also, modifying the value of this object’s current property doesn’t cause a re-render. This is unlike the setState update function return from the useState hook.

We use the onClick on the button to a click listener to it. So, this listener will be called when the user clicks the button.

App.jsx
const handleClick = () => { ref.current?.scrollIntoView({ behavior: 'smooth' }); };

In the handleClick listener, we call the scrollIntoView() method on the ref of the target div element to scroll down to it and display it to the user.

We set the behaviour option to smooth to make the element scroll into view in an animated way, instead of jumping straight to the element in the next frame – auto. auto is the default.

Scroll to dynamic element on click in React

We can do something similar to scroll to a dynamically created element in React:

App.jsx
import { useRef, useState } from 'react'; const allFruits = [ 'Apples', 'Bananas', 'Oranges', 'Grapes', 'Strawberries', 'Blueberries', 'Pineapples', 'Mangoes', 'Kiwis', 'Watermelons', ]; export default function App() { const ref = useRef(null); const [fruits, setFruits] = useState([...allFruits.slice(0, 3)]); const addFruit = () => { setFruits((prevFruits) => [...prevFruits, allFruits[prevFruits.length]]); }; const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); }; return ( <div> <div style={{ position: 'fixed', backgroundColor: 'white', bottom: 0, marginBottom: 10, }} > <button onClick={addFruit}>Add fruit</button> <button onClick={scrollToLastFruit} style={{ marginLeft: '8px' }}> Scroll to last </button> </div> <div style={{ height: '5rem' }} /> <div ref={ref}> {fruits.map((fruit) => ( <h2 key={fruit}>{fruit}</h2> ))} </div> <div style={{ height: '150rem' }} /> </div> ); }
Scrolling to a dynamic element on click in React.

Here we have a list of fruits displayed. The Add fruit button dynamically adds an item to the fruit list on click. Then the Scroll to last button scrolls to this item on click, as it’s the last in the list.

Like before, we use the onClick prop to set a click event listener on the button.

This time we set the ref on the list instead of the items since the items are created dynamically, and the last item will not be constant. Doing this sets the current property of the ref object to the DOM object that represents the list element.

In this listener, we use the lastElementChild property of the list element to get its last item element. Then we call scrollIntoView() on this last item to scroll down to it.

JavaScript
const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); };

Create and scroll to dynamic element on click

We can also combine the element creation and scroll as a single action caused by a button click.

To do this, we’ll add a useEffect hook to call scrollToLastFruit() whenever the fruits state array changes.

App.jsx
const addFruit = () => { setFruits((prevFruits) => [...prevFruits, allFruits[prevFruits.length]]); }; const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); }; // 👇 Call `scrollToLastFruit()` when `fruits` changes. useEffect(() => { scrollToLastFruit(); }, [fruits]);
Creating and scrolling to a dynamic element on click in React.

Here’s the full code for reference:

App.jsx
import { useEffect, useRef, useState } from 'react'; const allFruits = [ 'Apples', 'Bananas', 'Oranges', 'Grapes', 'Strawberries', 'Blueberries', 'Pineapples', 'Mangoes', 'Kiwis', 'Watermelons', ]; export default function App() { const ref = useRef(null); const [fruits, setFruits] = useState([...allFruits.slice(0, 3)]); const addFruit = () => { setFruits((prevFruits) => [...prevFruits, allFruits[prevFruits.length]]); }; const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); }; useEffect(() => { scrollToLastFruit(); }, [fruits]); return ( <div> <div style={{ position: 'fixed', backgroundColor: 'white', bottom: 0, marginBottom: 10, }} > <button onClick={addFruit}>Add fruit and scroll</button> </div> <div style={{ height: '5rem' }} /> <div ref={ref}> {fruits.map((fruit) => ( <h2 key={fruit}>{fruit}</h2> ))} </div> <div style={{ height: '150rem' }} /> </div> ); }

Key takeaways

  • To scroll to an element on click in React, set a ref on the target element, set a click listener on the element meant to cause the scroll, and in the click event listener, call the scrollIntoView() method on the ref object.
  • To scroll to a dynamically created element in React, set the ref on the list container and call scrollIntoView() on the target item element.
  • We can combine element creation and scrolling as a single action by using the useEffect hook to call scrollToLastFruit() whenever the state array changes.