VOOZH about

URL: https://www.geeksforgeeks.org/reactjs/how-to-scroll-to-a-particular-element-or-skip-to-content-in-reactjs/

⇱ How to scroll to a particular element or skip to content in React JS ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to scroll to a particular element or skip to content in React JS ?

Last Updated : 23 Jul, 2025

In this article, we will learn about how to scroll or skip a particular element in React JS, We can do this using React hook useRef and React styled-components.

Prerequisite:

Approach to implement particular element scroll/skip:

It is used to scroll to the specified element in the browser. Here, we use top or left or right or bottom as the first parameter to scroll the page in the desired direction.

The second parameter is the behavior (of the scroll). It tells us how the window is going to reach the specified element and has a default value of the auto. However, it's not compulsory to provide this parameter as the browser uses its default value in case it's not provided.

Types of behavior:

  • Auto behavior: It allows a straight jump "scroll effect" and takes us to the element. This is the default value of the behavior parameter as discussed above. 
  • Smooth behavior: It allows a smooth "scroll effect" through the page and takes us to the element.

Syntax:

//Auto behavior or Smooth behavior syntax
window.scrollTo({
top: 100px,
behavior: "auto" or "smooth"
});

Steps to Create React Application And Installing Module:

Step 1: Create a React application using the following command:

npx create-react-app react-scroll

Step 2: After creating your project folder i.e. example, move to it using the following command:

cd react-scroll

Step 3: Installing Required module dependencies:

npm install --save styled-components

Project Structure:

👁 Image

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"styled-components": "^6.1.1",
"web-vitals": "^2.1.4",
}

Example: When we click on the button the function gotoServices is getting triggered through onClick event. This top position of the Services element is accessed by the offsetTop property by writing Services.current.offsetTop which returns the top position (in pixels) relative to the top of the offsetParent element.

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000

Using default behavior (auto): See how it directly jumps to the element. 👁 Image

Using smooth behavior: See how it goes smoothly through the page. 👁 Image

Comment