I have a textarea and two buttons (up and down).
How can I scroll up and down line by line in the textarea using the up and down buttons with React.js.
Something like as if I'm writing a note and I move the text cursor up and down the paragraphs using the up and down keys on my keyboard.
Image: https://i.stack.imgur.com/9eEXU.png
Simplified code:
import React from "react";
export default function App() {
return (
<div>
<button>Up</button>
<br />
<textarea placeholder="YOUR NOTES" />
<br />
<button>Down</button>
</div>
);
}
A friend helped me out. I thought I should come back here and share the solution with everyone else who might need it in the future.
import React from "react";
const goUp = (id) => {
var maxScrollTop = id.scrollHeight - id.clientHeight;
if (id.scrollTop !== 0) {
id.scrollTo({
top: id.scrollTop - 10,
left: 0,
behavior: "smooth"
});
}
};
const goDown = (id) => {
var maxScrollDown = id.scrollHeight - id.clientHeight;
id.scrollTo({
top: id.scrollTop + 10,
left: 0,
behavior: "smooth"
});
};
export default function App() {
const okay = document.getElementById("text");
return (
<div>
<button onClick={() => goUp(okay)}>Up</button>
<br />
<textarea id="text" placeholder="YOUR NOTES" />
<br />
<button onClick={() => goDown(okay)}>Down</button>
</div>
);
}