hello everyone I am new at reactjs.
I want to scroll specific div instead of window
const handleScroll = (event) => {
window.scrollBy(100, 0);
}
You can use useRef
hook to give a reference that the component you want to scroll using React functional components. Then use scrollIntoView
to give a smooth scrolling behavior.
Here is a example:
import React, { useRef } from "react";
export default function App() {
const titleRef = useRef();
function handleClick() {
titleRef.current.scrollIntoView({ behavior: "smooth" });
}
return (
<article>
<h1 ref={titleRef}>A React article for Latin readers</h1>
Here is the content
<br />
<button onClick={handleClick}>Back to the top</button>
</article>
);
}
Use this js code
import React from "react";
const App = () => {
const myRef = React.useRef(null)
const scrollDiv = () => myRef.current.scrollIntoView()
return (
<>
<div ref={myRef}>Hello World</div>
<button onClick={scrollDiv }> Scroll </button>
</>
)
}
Or
import React from "react";
const App = () => {
const [scrollDiv, myRef] = React.useScroll()
useEffect(executeScroll, [])
return (
<div ref={myRef}>Hello World</div>
);
}
Or
Instead of using js code use css for that.
<div className="list_item">
<ul>
<li>...</li>
<li>...</li>
<li>...</li>
.
.
.
<li>...</li>
</ul>
</div>
In your css file just use like this...
.list_item {
overflow: auto;
}
If you want styled scroll use below code
.list_item {
overflow: auto;
}
.list_item::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
background-color: light-gray;
}
.list_item::-webkit-scrollbar {
width: 3px;
background-color: light-gray;
}
.list_item::-webkit-scrollbar-thumb {
background-color: dark-gray;
}