hello I have a few buttons and I want to scroll to them when clicked.
const [active, setActive] = useState(0); useEffect(() => { // I´m not using useRef. is there other way to automatically scroll to the element and stop at 0 0 of the page? }) <div style={{height: '10000px'}} /> <button onClick={() setActive(1)}>button 1</button> <button onClick={() setActive(2)}>button 2</button> <button onClick={() setActive(3)}>button 3</button> <div style={{height: '10000px'}} />
as you can see there´s a lot of scroll caused by those 2 divs. the idea is to scroll down and when you reach the buttons and click the one you need. the page scrolls to that button leaving it in the top of the page
image 1: scroll in random position image 2: when you click on button 1 image 3: when you click on button 2 image 4: when you click on button 3
Advertisement
Answer
For scrolling react view to top there is a simple function.
use window.scrollTo(0, 0);
inside your code try this.
<button onClick={()=> window.scrollTo(0, 0) }>button 1</button>
edited:
I could come up with this solution after you edited your question.
import React, { useRef } from "react"; export default function App() { const button1Ref = useRef(); const button2Ref = useRef(); const button3Ref = useRef(); const handleScroll = ref => { window.scrollTo({ behavior: "smooth", top: ref.current.offsetTop }); }; return ( <div className="App"> <div style={{ height: "10000px" }} /> <div> <button ref={button1Ref} onClick={() => handleScroll(button1Ref)}> button 1 </button> </div> <div> <button ref={button2Ref} onClick={() => handleScroll(button2Ref)}> button 2 </button> </div> <div> <button ref={button3Ref} onClick={() => handleScroll(button3Ref)}> button 3 </button> </div> <div style={{ height: "10000px" }} /> </div> ); }
Please try it out. Let me know if this is what you asked for.
Edited after question asked in comment for using single component with Ref and using that component in multiple numbers:
If you want to use a single component for button then try this,
import React, { useRef } from "react"; export default function App() { return ( <div className="App"> <div style={{ height: "10000px" }} /> <MyButton>button 1</MyButton> <MyButton>button 2</MyButton> <MyButton>button 3</MyButton> <div style={{ height: "10000px" }} /> </div> ); } const MyButton = props => { const buttonRef = useRef(); const handleScroll = () => { window.scrollTo({ behavior: "smooth", top: buttonRef.current.offsetTop }); }; return ( <div> <button ref={buttonRef} onClick={handleScroll}> {props.children} </button> </div> ); };