malte-wessel / react-custom-scrollbars

React scrollbars component
http://malte-wessel.github.io/react-custom-scrollbars/
MIT License
3.2k stars 577 forks source link

Auto scroll to the End when a new message comes #397

Open HassanAbbas5 opened 3 years ago

HassanAbbas5 commented 3 years ago

I used ur scrollbar in my conversation i want to autoscroll to bottom of the conversation whenever i receive a new message please help or is there any method so that ( i will set scrollbar to always on bottom )? Thanks in advance

TheDarkStrix commented 3 years ago

You could do something like this

This scroll to bottom initially and scrolls to bottom when there is a change in the chat list


const ScrollbarWrapper = (props) => {
  const scrollBar = useRef();

  const handleOnScroll = (e) => {
    if (e.target.scrollTop === 0) {
      props.scrollFnc();
    }
  };

// props.chat is a state that holds all the chat

  useEffect(() => {
    console.log("scrollbar change detected");
    if (scrollBar) scrollBar.current.scrollToBottom();
  }, [scrollBar, props.chat]);

  return (
    <Scrollbars
      onScroll={scrollHandler }
      universal={true}
      autoHide={true}
      autoHeight={true}
      ref={scrollBar}
      autoHeightMax={props.autoHeightMax}
      style={{
        overflowX: "hidden",
        margin:"1em 0em",
        padding:"0em",
      }}
      renderTrackHorizontal={(props) => (
        <div {...props} className="track-horizontal" />
      )}
      renderTrackVertical={(props) => (
        <div {...props} className="track-vertical" />
      )}
      renderThumbHorizontal={(props) => (
        <div {...props} className="thumb-horizontal" />
      )}
      renderThumbVertical={(props) => (
        <div {...props} className="thumb-vertical" />
      )}
      renderView={(props) => <div {...props} className="view" />}
    >
      {props.children}
    </Scrollbars>
  );
};

export default ScrollbarWrapper;