I want to link from one view to another and then scroll to a specific element. I'm not intrested in any animations, only want to have the element in view. The link from one view to another is done through react router.
I guess I could somehow create references on the elements I want to scroll to and pass them to the other view, but don't know if that's the correct approach?
A simple example. (Not working, but hopefully you understand what I want to achieve)
const ViewOne = () => {
const navigate = useNavigate(); // From react-router v6
return (
<p onClick={() =>
{
navigate("ViewTwo");
// What more do I have to add?
}}>
Link to section two, in view two
</p>
);
}
export default ViewOne;
const ViewTwo = () => {
return (
<>
<section style={{height: "100vh"}}></section>
<section style={{height: "100vh"}}>
Scroll here?
</section>
<section style={{height: "100vh"}}></section>
</>);
}
export default ViewTwo;
I'm using react-router-dom-v6
CodePudding user response:
you can use "useRef" to scroll to that position with click event or try useEffect for scroll to that position after component rendered.
const ViewTwo = () => {
const scroller = useRef(null)
const executeScroll = () => scroller.current.scrollIntoView()
return (
<>
<section style={{height: "100vh"}}></section>
<section ref={scroller} style={{height: "100vh"}}>
Scroll here?
</section>
<button onClick={executeScroll}> Click to scroll </button>
<section style={{height: "100vh"}}></section>
</>);
}
export default ViewTwo;
CodePudding user response:
Give the sections you want to target and scroll to id
attributes. Pass a target id in route state. Use a useEffect
hook to target the element and scroll it into view.
Example:
const ViewOne = () => {
const navigate = useNavigate(); // From react-router v6
return (
<p
onClick={() => {
navigate("/viewtwo", { state: { targetId: "section2" } });
}}
>
Link to section two, in view two
</p>
);
};
...
const ViewTwo = () => {
const { state } = useLocation();
const { targetId } = state || {};
useEffect(() => {
const el = document.getElementById(targetId);
if (el) {
el.scrollIntoView();
}
}, [targetId]);
return (
<>
<section id="section1" style={{ height: "100vh" }}></section>
<section id="section2" style={{ height: "100vh" }}>
Scroll here?
</section>
<section id="section3" style={{ height: "100vh" }}></section>
</>
);
};
...
<Router>
<Routes>
...
<Route path="/viewone" element={<ViewOne />} />
<Route path="/viewtwo" element={<ViewTwo />} />
...
</Routes>
</Router>