Container
Import container in each route and wrap route's content in it:
import { ScrollContainer } from 'react-nice-scroll';
import 'react-nice-scroll/dist/styles.css';
const Index = () => {
return (
<ScrollContainer>
<section style={{ height: '300vh' }}>
<h1>Hello World!</h1>
</section>
</ScrollContainer>
);
};
export default Index;
Demo
Check demo.
ScrollContainer Props
Props | Value Type | Default Value |
---|---|---|
damping | number | 0.075 |
thumbMinSize | number | 20 |
renderByPixels | boolean | false |
alwaysShowTracks | boolean | false |
continuousScrolling | boolean | true |
activeSmoothScrollOnTouchDevice | boolean | false |
disableSmoothScroll | boolean | false |
delegateTo | EventTarget | undefined | undefined |
note
react-nice-scroll is made top on smooth-scrollbar plugin. Check smooth-scrollbar to understand props.(disableSmoothScroll and activeSmoothScrollOnTouchDevice have provided by react-nice-scroll)
tip
Recommend to disable smooth scroll in touch devices. Because touch devices have their own smooth scrolling so using a custom smooth scroll is not appropriate and also may cause performance issues. But if you prefer to use the custom smooth scroll on touch devices, feel free and just set activeSmoothScrollOnTouchDevice to true.
Scroll To
Scroll to specific section or element:
import { ScrollContainer, useGlobalState } from 'react-nice-scroll';
import 'react-nice-scroll/dist/styles.css';
const Index = () => {
const [smoothScrollBar] = useGlobalState('smoothScrollBar');
const handleScrollTo = () => {
if (smoothScrollBar) {
const el = document.querySelector('#scroll-here') as HTMLElement;
smoothScrollBar.scrollIntoView(el);
}
};
return (
<ScrollContainer>
<button onclick="handleScrollTo">Scroll To</button>
<section style={{ height: '300vh' }}>
<h1>Hello World!</h1>
</section>
<section id="scroll-here">
<h1>Scroll Here!</h1>
</section>
</ScrollContainer>
);
};
export default Index;
tip
When disableSmoothScroll is true or in touch devices when activeSmoothScrollOnTouchDevice is false, react-nice-scroll uses native scroll and scrolling to specific section or element can easily handle in pure Javascript. So the approach in above works only when smooth scrolling is active.
Pause/ Resume Scroll
Disable temporally scrolling and then enable it:
import { ScrollContainer, useGlobalState } from 'react-nice-scroll';
import 'react-nice-scroll/dist/styles.css';
const Index = () => {
const [smoothScrollBar] = useGlobalState('smoothScrollBar');
const [allowScroll, setAllowScroll] = useGlobalState('allowScroll');
const handleAllowScroll = () => {
if (smoothScrollBar) {
smoothScrollBar.updatePluginOptions('allowScroll', { allow: !allowScroll });
setAllowScroll(!allowScroll);
}
};
return (
<ScrollContainer>
<button onclick="handleAllowScroll">Pause/ Start Scroll</button>
<section style={{ height: '300vh' }}>
<h1>Hello World!</h1>
</section>
</ScrollContainer>
);
};
export default Index;