Iam having two buttons(Home, Contact Us) in my header and iam having the content for "Home and Contact Us" in a div on the same page, while im clicking the home or contact button it should scroll to that particular div using React-Router Since iam new to these concepts i can't find a correct solution.
How to scroll to the particular div on button click in a single page application using react-router?
Asked
Active
Viewed 624 times
1 Answers
1
Why you want React-Router
for this?
Can't you directly wrap the buttons into <a>
tag and provide a href
attribute to <a>
tag with the id
of section where you want to scroll.
e.g.
<a href="#home"><button>Home</button></a>
Somewhere in you component,
<div id="home">
...
</div>
For smooth scrolling effect you can add this css,
html{scroll-behavior:smooth}
Updated
On the basis of comment, you can make use of react-router-hash-link
.
yarn add react-router-hash-link
or
npm install --save react-router-hash-link
// In YourComponent.js
...
import { HashLink as Link } from 'react-router-hash-link';
...
// Use it just like a RRv4 (to can be a string or an object, see RRv4 api for details):
<Link to="/some/path#with-hash-fragment">Link to Hash Fragment</Link>

ravibagul91
- 20,072
- 5
- 36
- 59
-
Actually that's my requirement sir, I am using reactjs for view and i have two buttons namely contact and about, while im clicking on those buttons it should scroll to that particular div and the url should also change.. – SJ Purusothaman Jun 24 '19 at 06:14