I've got a React Component with several nested components. For page navigation I have a few buttons on the top. The question is, how to scroll the page to the nested react component when a certain button is clicked, is it possible to do so without using jquery libs?
render() {
return (
<div>
<button onClick={(e) => { console.log('Scrolling to Item 1');}}>Button0</button>
<button onClick={(e) => { console.log('Scrolling to Item 2');}}>Button1</button>
<Layout>
<Item>
<Content>
...
</Content>
</Item>
<Item>
<Content>
...
</Content>
</Item>
</Layout>
}
</div>
);
}
Scroll to an element on click in React js. 2. Now open terminal inside your react js project and install react-scroll. 3. Go to your src folder and create a components folder. 4. Now inside your components folder create your first component with the name header.js. 5. Open the header.js file in your ...
The react-scroll-to-top library is a lightweight, customizable button component, that scrolls to the top of the page when clicked. This component is analogous to our own, but you don't have to code it up yourself. Naturally, it only appears once you've scrolled down enough that it makes sense for it to appear.
Put an id attribute ('myTarget') to your target component and replace the button with a link (href: '#mytarget'). This does not work with fixed headers, unfortunately. Use scrollIntoView method to scroll to the specific Element/ Component If you are using typescript.
Basic Knowledge of useRef React hooks. Basic Setup: You will start a new project using create-react-app so open your terminal and type. Now go to your react-scroll folder by typing the given command in the terminal. Required module: Install the dependencies required in this project by typing the given command in the terminal.
Have you tried using an anchor?
Put an id attribute ('myTarget') to your target component and replace the button with a link (href: '#mytarget').
This does not work with fixed headers, unfortunately.
Using React hooks and no 3rd party packages:
import { useRef } from 'react'
const firstItemRef = useRef(null);
<Item ref={firstItemRef}>
<button onClick={() => firstItemRef.current.scrollIntoView()}
Create a reference using useRef
const trackButton = useRef();
Use scrollIntoView method to scroll to the specific Element/ Component
trackButton.current.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With