Open In App

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

Last Updated : 12 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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.

Javascript




import { Fragment } from "react";
import ScrollPage from "./components/ScrollPage";
function App() {
    return (
        <Fragment>
            <ScrollPage />
        </Fragment>
    );
}
 
export default App;


Javascript




//Styles.js
 
import styled from 'styled-components';
 
export const Heading = styled.h1`
   margin: 0;
   padding: 0;
   text-align: center;
   color: green;
`;
 
export const Button = styled.button`
  padding: 20px;
  font-size: 20px;
  position: relative;
  left: 42%;
  margin: 20px;
`;
 
export const Para = styled.p`
  padding-left: 40px;
  padding-right: 40px;
`;
 
export const Margin = styled.div`
  margin-top: 610px;
  margin-bottom: 500px;
  background-color: black;
  color: white;
  padding: 20px;
`;


Javascript




//ScrollPage.js
 
import React, { useRef } from "react";
import { Heading, Button, Para, Margin } from "./Styles";
const ScrollPage = () => {
    const ServicesRef = useRef(null);
 
    const gotoServices = () =>
        window.scrollTo({
            top: ServicesRef.current.offsetTop,
            behavior: "smooth",
            // You can also assign value "auto"
            // to the behavior parameter.
        });
 
    return (
        <div>
            <Heading>GeeksForGeeks</Heading>
            <Button onClick={gotoServices}>Scroll to Services</Button>
 
            <Margin ref={ServicesRef}>
                <Heading>GeeksForGeeks Services</Heading>
 
                <Para>
                    Lorem Ipsum è un testo segnaposto utilizzato
                    nel settore della tipografia e della stampa.
                    Lorem Ipsum è considerato il testo segnaposto
                    standard sin dal sedicesimo secolo, quando un anonimo
                    tipografo prese una cassetta di caratteri e li
                    assemblò per preparare un testo campione. È
                    sopravvissuto non solo a più di cinque secoli, ma
                    anche al passaggio alla videoimpaginazione, pervenendoci
                    sostanzialmente inalterato. Fu reso popolare, negli
                    anni ’60, con la diffusione dei fogli di caratteri
                    trasferibili “Letraset”, che contenevano passaggi del
                    Lorem Ipsum, e più recentemente da software
                    di impaginazione come Aldus PageMaker, che includeva
                    versioni del Lorem Ipsum.
                </Para>
 
                <Para>
                    Lorem Ipsum è un testo segnaposto utilizzato nel
                    settore della tipografia e della stampa. Lorem
                    Ipsum è considerato il testo segnaposto standard
                    sin dal sedicesimo secolo, quando un anonimo tipografo
                    prese una cassetta di caratteri e li assemblò per preparare
                    un testo campione. È sopravvissuto non solo a più di
                    cinque secoli, ma anche al passaggio alla videoimpaginazione,
                    pervenendoci sostanzialmente inalterato. Fu reso popolare,
                    negli anni ’60, con la diffusione dei fogli di caratteri
                    trasferibili “Letraset”, che contenevano passaggi del Lorem
                    Ipsum, e più recentemente da software di impaginazione come
                    Aldus PageMaker, che includeva versioni del Lorem Ipsum.
                </Para>
            </Margin>
        </div>
    );
};
 
export default ScrollPage;


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.

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads