Reputation: 732
How can I stop the scroll Into View when the screen reach the reference (inside the method scroll) ? (When the screen reaches its reference, I scroll a little bit up and the code atomatcaly come back to the reference)
interface Props {
section: number
}
const Home = ({ section }: Props) => {
const sectionRef1: any = useRef(React.createRef());
const sectionRef2: any = useRef(React.createRef());
const scroll = (ref: any) => {
ref.current.scrollIntoView({
behavior: 'smooth',
block: 'start',
});
};
function scrollToSection(section: number) {
if (section === 1) {
scroll(sectionRef1);
}
else if (section === 2) {
scroll(sectionRef2);
}
else if (section === 3) {
//TODO: active button
}
}
scrollToSection(section);
return (
<div>
<div ref={sectionRef1} />
<Carrousel></Carrousel>
<div ref={sectionRef2} className="margin_top_portrait" />
<Portrait></Portrait>
</div>
);
}
export default Home;
I'm afraid that this funcion will never finish ... and it's asynchronous.
Thanks in advance for your help.
Upvotes: 0
Views: 900
Reputation: 6325
If you want to run the scroll method only when the section changes, you can use the useEffect hook of react:
useEffect(() => {
scrollToSection(section);
}, [section]);
This will execute the scrollToSection
method the first time the component is mounted and every time the section
prop changes.
Upvotes: 1