How can I scroll right when inserting a character in draft js?

Viewed 379

With draft-js and a styled component, I made an inline input intended for a calculator. When I type into it with a keyboard, it works as expected:

enter image description here

When I press the plus button, a "+" is added to the text, but the view doesn't scroll:

enter image description here

Here's the behavior and the code in a codesandbox: https://codesandbox.io/s/charming-brattain-mvkj3?from-embed=&file=/src/index.js

How can I get the view to scroll when text is added programmatically like that?

1 Answers

At long last, I figured out a solution. I added this to the calculator input component:

const shell = React.useRef(null);
const [scrollToggle, setScrollToggle] = React.useState(
  { value: false }
);

React.useEffect(() => {
  const scrollMax = shell.current.scrollWidth - shell.current.clientWidth;
  shell.current.scrollLeft += scrollMax;
}, [scrollToggle]);

const scrollToEnd = () => {
  setScrollToggle({ value: !scrollToggle.value });
};

Then at the end of the insertChars function I added scrollToEnd();.

And I set ref={shell} on <InputShell>

Related