Saturday, November 16, 2024
Google search engine
HomeLanguagesHow to scroll to a particular element or skip to content in...

How to scroll to a particular element or skip to content in ReactJS ?

The following example covers how to scroll to an element of a webpage in React JS using useRef() hook.

Prerequisite:

  • Basic knowledge of npm & create-react-app command.
  • Basic knowledge of styled-components.
  • Basic Knowledge of useRef React hooks.

Basic Setup: You will start a new project using create-react-app so open your terminal and type.

npx create-react-app react-scroll

Now go to your react-scroll folder by typing the given command in the terminal.

cd react-scroll

Required module: Install the dependencies required in this project by typing the given command in the terminal.

npm install --save styled-components

Now create the components folder in src then go to the components folder and create two files ScrollPage.jsand Styles.js.

Project Structure: The file structure in the project will look like this.

The scrollTo method: 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:

  1. 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. 

    Syntax:

    window.scrollTo({
         top: 100px
         // Browser uses the default value in 
         // case it is not provided.
    });
    window.scrollTo({
         top: 100px,
         behavior: "auto"
    });
  2. Smooth behavior: It allows a smooth “scroll effect” through the page and takes us to the element.

    Syntax:

     window.scrollTo({
            top: 100px,
            behavior: "smooth"
        });

Example: Scrolling down to the Services element, that’s where the role of useRef() hook comes into play. We create a useRef object ServicesRef which is initialized to null. This object has a property called .current. The value is always continued in the refObject.current property.

When we click on the button the function gotoServices is getting triggered through onClick event and it sets the top parameter of scrollTo function to the value of the top position of our Services element (in pixels). 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.

For example, if our Services element is 100px away from the parent element, i.e. div element in this case, then it would assign 100px to the top parameter of scrollTo function which takes us 100px down the page. That’s why we assign the value of refObject.current.offsetTop to the top parameter here.

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;


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;
`;


App.js




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


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/, you will see the following output.

  • Using default behavior (auto): See how it directly jumps to the element.
  • Using smooth behavior: See how it goes smoothly through the page.
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments