In React, you can use the onClick
event handler along with the scrollIntoView()
method to scroll to a specific element when a click event occurs. Here’s an example of how you can achieve this:
First, make sure you have a reference to the element you want to scroll to. You can use the useRef
hook to create a ref in a functional component or create a class component with a ref property.
import React, { useRef } from 'react';
function MyComponent() {
const scrollRef = useRef(null);
const handleClick = () => {
scrollRef.current.scrollIntoView({ behavior: 'smooth' });
};
return (
<div>
<button onClick={handleClick}>Scroll Down</button>
<div ref={scrollRef}>
{/* Content to scroll to */}
</div>
</div>
);
}
export default MyComponent;
In the above example, we create a ref using the useRef
hook and assign it to the scrollRef
variable. We then define a handleClick
function that will be called when the button is clicked. Inside this function, we use the scrollIntoView()
method on the scrollRef.current
to scroll to the associated element.
If your destination is another component, you can pass a function or a callback from the parent component to the child component. This function can be invoked in the child component’s onClick
event handler to trigger the scroll functionality. Here’s an example:
Parent Component:
import React, { useRef } from 'react';
import ScrollToComponent from './ScrollToComponent';
function ParentComponent() {
const scrollRef = useRef(null);
const scrollToComponent = () => {
scrollRef.current.scrollIntoView({ behavior: 'smooth' });
};
return (
<div>
<button onClick={scrollToComponent}>Scroll Down</button>
<ScrollToComponent scrollRef={scrollRef} />
</div>
);
}
export default ParentComponent;
Child Component (ScrollToComponent):
import React from 'react';
function ScrollToComponent({ scrollRef }) {
return (
<div ref={scrollRef}>
{/* Content to scroll to */}
</div>
);
}
export default ScrollToComponent;
In this example, the ParentComponent
contains the button and the ScrollToComponent
. The scrollRef
is passed as a prop to the ScrollToComponent
. The scrollRef
is then assigned to the ref
attribute of the target element within the ScrollToComponent
.
When the button is clicked in the ParentComponent
, it invokes the scrollToComponent
function, which scrolls to the target element referenced by scrollRef
within the ScrollToComponent
.