Stop scroll position from moving to the bottom

The code i added is just an example to show my problem in a simpler way. But the idea is that i have this titles array that gets looped through and shown on screen and when you click on a title its sub-titles show up below. Kinda like a drop down element. The problem is when i for example first select the first title and then scroll down to the eight title and click on it the last sub-title elements become visible and i have to scroll back up to see the top ones. How can i stop scroll position from jumping to the bottom when i click on a title element.

const Hold = () => {
  interface TitleItem {
    id: number;
    title: string;
  }

  interface SubTitleItem {
    id: number;
    subTitle: string;
  }

  const titleArray: TitleItem[] = [
    { id: 1, title: "First Item" },
    { id: 2, title: "Second Item" },
    { id: 3, title: "Third Item" },
    { id: 4, title: "Fourth Item" },
    { id: 5, title: "Fifth Item" },
    { id: 6, title: "Sixth Item" },
    { id: 7, title: "Seventh Item" },
    { id: 8, title: "Eighth Item" },
    { id: 9, title: "Ninth Item" },
    { id: 10, title: "Tenth Item" },
  ];

  const subTitleArray: SubTitleItem[] = [
    { id: 1, subTitle: "First Sub Item" },
    { id: 2, subTitle: "Second Sub Item" },
    { id: 3, subTitle: "Third Sub Item" },
    { id: 4, subTitle: "Fourth Sub Item" },
    { id: 5, subTitle: "Fifth Sub Item" },
    { id: 6, subTitle: "Sixth Sub Item" },
    { id: 7, subTitle: "Seventh Sub Item" },
    { id: 8, subTitle: "Eighth Sub Item" },
    { id: 9, subTitle: "Ninth Sub Item" },
    { id: 10, subTitle: "Tenth Sub Item" },
  ];

  const [selectedTitle, setSelectedTitle] = useState<TitleItem | null>(null);

  return (
    <div className="p-10 h-screen">
      {titleArray.map((title) => (
        <div key={title.id}>
          <div
            onClick={() => {
              setSelectedTitle(title);
            }}
          >
            {title.title}
          </div>
          {selectedTitle && selectedTitle.id === title.id && (
            <div>
              {subTitleArray.map((subTitle) => (
                <div className="h-28 border p-5 mb-2" key={subTitle.id}>
                  {subTitle.subTitle}
                </div>
              ))}
            </div>
          )}
        </div>
      ))}
    </div>
  );
};

export default Hold;

Thanks in advance.

Leave a Comment