edile
edile

Reputation: 21

React scroll nav horizontally on button click

i have a navbar and i want to scroll it horizontally. I use "Tab" and "Tabs" from react-bootstrap. I couldn't figure out how to do this. ( I tried to wrap nav with div, but it didn't work because every tab has its own items )

I tried this:

const outsider = document.getElementsByClassName('products-tabs sub-tabs nav nav-tabs');
const distance = 200;
const scrollLft = () => {
  outsider.scrollLeft -= 900;
  console.log(outsider);
};

<Tab
  className="products-tab"
  id="products-tab"
  eventKey={index}
  title={subcategories.categoryName}
  key={`${index + 1}_tab`}
>
  {subcategories?.subcategories?.length > 1 ? (
    <>
      <Button onPress={scrollLft} className="brand-arrow-button">
        <i className="icon-Arrow_Simple_left" align="left" />
      </Button>
      <Button
        onPress={() => onClickLeft()}
        className="brand-arrow-button-right"
      >
        <i className="icon-Arrow_simple_rightt" align="left" />
      </Button>
      <div id="menum">
        <Tabs
          className="products-tabs sub-tabs"
          defaultActiveKey="sub-0"
          id="menu-subcategories"
          onSelect={e => {
            const selectedTabIndex = parseInt(e.split('-')[1], 10);
            setActiveSubcategory(selectedTabIndex);
          }}
        >
          {subcategories?.subcategories
            ?.concat(subcategories?.subcategories)
            .map((subcategoryItem, subIndex) => (
              <Tab
                eventKey={'sub-' + subIndex}
                title={subcategoryItem?.name}
                key={`${subIndex + 1}_subTab`}
              >
                **Items
              </Tab>
            ))}
        </Tabs>

And this is my css:

&.sub-tabs {
        border-radius: 15px;
        margin-left: -1px;
        margin-right: -16px;
        padding-bottom: 1px;
        margin-top: 10px;
        flex: none;
        overflow-x: scroll;
        white-space: nowrap !important;

When i click to the button, nothing happens.

This is the console output: enter image description here

Upvotes: 1

Views: 4144

Answers (1)

In React, you can use the useRef() Hook to get the reference of a component (similar to document.getElementsByClassName()). Then, you can apply horizontal scrolling using element.current.scrollLeft.

Example:

import { useRef } from 'react'

const App = () => {

    const scrollElement = useRef(null)

    const scrollLeft = () => {

        scrollElement.current.scrollLeft = 50

    }

    return (
        <div className = 'App'>
            <div className = 'ScrollMenu' ref = {scrollElement}>
                <a href = '#home'>Home</a>
                <a href = '#news'>News</a>
                <a href = '#contact'>Contact</a>
                <a href = '#about'>About</a>
            </div>
            <button onClick = {scrollLeft}>Click me</button>
        </div>
    )
}

Here is a live example.

Upvotes: 1

Related Questions