简体   繁体   中英

What is the best way to implement horizontal scroll on list in reactJS? And also can i use getElementById in react code?

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 在此处输入图像描述

**Any suggession / feedback will be appreciated.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM