Yong Park
Yong Park

Reputation: 1

React How do I make the page allows scrolled down?

I'm trying to create a chat message and I have no idea how to make the chat be scrolled down every time. When the user inputs new messages, I want it to be always scrolled down so that we can see the new message at the bottom. I feel like this is what needs to be edited.

const MessageContainer = styled.div`
    display: flex;
    flex-direction: column;
    overflow-y: auto;
`

Upvotes: 0

Views: 63

Answers (2)

Utkarsh Gupta
Utkarsh Gupta

Reputation: 21

You can keep a dummy div at the bottom of your chat and then scroll to it whenever your component is updated (i.e. state updated as new messages are added):

const [message, setMessage] = useState([]);
const [text, setText] = useState(1);
const messagesEndRef = useRef(null);
const scrollToBottom = () => {
  messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
};
useEffect(scrollToBottom, [message]);

const addText = () => {
  setMessage([...message, text]);
  setText((data) => data + 1);
}

return (
  <div className="App">
    <div className="data">
      {message.map(m => (
        <span key={m}>{m}</span>
      ))}
      <div ref={messagesEndRef} />
    </div>
    <button onClick={addText} className={'button'}>Add Text</button>
  </div>
);

https://codesandbox.io/s/great-feynman-5m3i7?file=/src/App.js

Upvotes: 2

Jay Lu
Jay Lu

Reputation: 1745

You can try :

const MessageContainer = styled.div`
    display: flex;
    flex-direction: column-reverse;
    overflow-y: auto;
`

Or

I make sample(CodeSandBox) for you, but I'm not sure if this is what you want.

Edit TextField selectionStart

It likes :

enter image description here

Hope to help you !

Upvotes: 0

Related Questions