I have to implement horizontal scroll for the list of items but with the back and forward arrow button. Following is what i implemented but i want to know if there is another best way to do it may be by using REFS.

  const scrollLeft = () => {
     let scrollPosition = document.getElementById('buttonRow')?.scrollLeft;
     if (scrollPosition) {
     scrollPosition = scrollPosition - 80;
     document.getElementById('buttonRow')?.scroll({ left: scrollPosition, behavior: 'smooth' 
      });
    }
  };

const scrollRight = () => {
  let scrollPosition = document.getElementById('buttonRow')?.scrollLeft;
  if (scrollPosition || scrollPosition === 0) {
  scrollPosition = scrollPosition + 80;
  document
    .getElementById('buttonRow')
    ?.scroll({ left: scrollPosition, behavior: 'smooth' });
  }
};
#Pivots types are array i am using, which i want to display.
let PivotTypes = ['item1', 'item2', 'item3', 'item4']

This is my jsx

        <LeftArrowButton onClick={() => scrollLeft()}>
          <StyledLeftArrow />
        </LeftArrowButton>
        <InlineContainer>
          <ButtonRow id="buttonRow">
            {PivotTypes.map(pivotType => {
              return (
                <PivotButton
                  style={{
                    backgroundColor: activePivots.some(
                      pivot => pivot === pivotType
                    )
                      ? '#00a1de'
                      : '#8b8b8b',
                  }}
                  id={pivotType + 'PivotButton'}
                >
                  {pivotType}
                </PivotButton>
              );
            })}
          </ButtonRow>
        </InlineContainer>
        <RightArrowButton onClick={() => scrollRight()}>
          <StyledRightArrow />
        </RightArrowButton>

This works but I am not happy with the implementation as it has getElementById, which i feel is not react way of doing it :/

Note: for ui i am using @material-ui/core package

UI is something like this enter image description here

**Any suggession / feedback will be appreciated.

1

There are 1 best solutions below

3
On

If I'm understanding correctly you just want to add a horizontal scroll to your html tag.

To do that you can use css.

overflow-x:scroll;