This all in a single page. When I press the Button
in NavBar
, I want the screen to scroll to SubscriptionForm
component. I have tried using useRef
and forwardRef
while following this tutorial but it doesn't seem to work in my case. I have also tried react-scroll's <Link />
and it works with essentially two lines of code. But, what I want to know is how to make it possible without the use of react-scroll.
My folder and code structure is as follows -
src
|-- Home
| |-- Home.js
| |-- SubscriptionForm
| | |-- SubscriptionForm.js
|-- NavBar
| |-- NavBar.js
|-- App.js
In SubscriptionForm.js
-
const SubscriptionForm = () => {
return (
<Form>...</Form>
)
}
In Home.js
-
import SubscriptionForm from './SubscriptionForm/SubscriptionForm'
const Home = () => {
return (
<div>
// other components
<SubscriptionForm />
</div>
)
}
In NavBar.js
-
const NavBar = () => {
return (
<div>
// other stuff
<Button />
</div>
)
}
In App.js
-
import NavBar from './NavBar/NavBar'
import Home from './Home/Home'
const App = () => {
return (
<div>
<NavBar />
<Home />
</div>
)
}
CodePudding user response:
Solved it by using useRef
and fowrawdRef
.
You will need to create a ref inside App
component and forward it all the way through, to the form
element using forwardRef
.
Then pass the ref as a prop and use it in the NavBar
component.
Working example: Sandbox