When clicking a link, navigate to a specific element in React without scrolling

79 Views Asked by At

In my user's profiles page in React, when clicking on an image, it currently scrolls to that specific image within the entire images page. However, I want it to navigate directly to that image element without scrolling. I want to make this change because it becomes very lag when there are 100 pictures in a user's profile.

Is there any method in react or nextjs to achieve this?

1

There are 1 best solutions below

1
Harishbabu On

You can create refs for each image and use the scrollIntoView method to bring the selected image into the view. Here's an example using React and Next.js:

1)Assuming you have a list of images in your component:

// ImageList.js

import React, { useRef } from 'react';

const ImageList = ({ images }) => {
  return (
    <div>
      {images.map((image, index) => (
        <img
          key={index}
          src={image.src}
          alt={`Image ${index + 1}`}
          onClick={() => handleImageClick(index)}
        />
      ))}
    </div>
  );
};

export default ImageList;
  1. Now, in the same component or a parent component, you can define a ref for each image and create a function to handle the image click event:

// UserProfile.js

import React, { useRef } from 'react';
import ImageList from './ImageList';

const UserProfile = () => {
  const imageRefs = useRef([]);

  const handleImageClick = (index) => {
    if (imageRefs.current[index]) {
      imageRefs.current[index].scrollIntoView({ behavior: 'smooth' });
    }
  };

  return (
    <div>
      <h2>User Profile</h2>
      <ImageList images={yourImageArray} imageRefs={imageRefs} />
    </div>
  );
};

export default UserProfile;

3)In the ImageList component, update the img elements to use the refs:

// ImageList.js

const ImageList = ({ images, imageRefs }) => {
  return (
    <div>
      {images.map((image, index) => (
        <img
          key={index}
          src={image.src}
          alt={`Image ${index + 1}`}
          onClick={() => handleImageClick(index)}
          ref={(ref) => (imageRefs.current[index] = ref)}
        />
      ))}
    </div>
  );
};

export default ImageList;