score:2
Accepted answer
you cannot pass refs as props to other components with the name prop without using forwardref on the commponent. you need to assign another name to it in order for it to work, for example innerrefs.
also to pass on refs as prop to the route component, make use of render prop method
app.tsx
import react, { useeffect, useref } from "react";
import { browserrouter, route, navlink, uselocation } from "react-router-dom";
import home from "./pages/home";
import "./styles.css";
const header = ({ innerrefs }) => {
const location = uselocation();
useeffect(() => {
console.log("location", location.pathname);
switch (location.pathname) {
case "/about":
scrollsmoothhandler(innerrefs.aboutref);
break;
case "/contact":
scrollsmoothhandler(innerrefs.contactref);
break;
case "/hero":
scrollsmoothhandler(innerrefs.heroref);
break;
default:
scrollsmoothhandler(innerrefs.homeref);
break;
}
}, [location, innerrefs]);
const scrollsmoothhandler = innerref => {
console.log("triggered.");
console.log(innerref.current);
innerref.current.scrollintoview({ behavior: "smooth" });
};
return (
<>
<navlink to="/hero" activeclassname="selected">
hero
</navlink>
<navlink to="/about" activeclassname="selected">
about
</navlink>
<navlink to="/contact" activeclassname="selected">
contact
</navlink>
</>
);
};
function app() {
const homeref = useref(null);
const heroref = useref(null);
const aboutref = useref(null);
const contactref = useref(null);
return (
<div ref={homeref} classname="app">
<browserrouter>
<header innerrefs={{ aboutref, contactref, heroref, homeref }} />
<route
exact
to="/"
render={routeprops => (
<home
{...routeprops}
innerrefs={{ aboutref, contactref, heroref, homeref }}
/>
)}
/>
// more routes here.
</browserrouter>
</div>
);
}
export default app;
home.tsx
import react, { fragment, forwardref, useref } from "react";
import "../styles.css";
const hero = forwardref((props, ref) => {
return (
<section ref={ref}>
<h1>hero section</h1>
</section>
);
});
const about = forwardref((props, ref) => {
return (
<section ref={ref}>
<h1>about section</h1>
</section>
);
});
const contact = forwardref((props, ref) => {
return (
<section ref={ref}>
<h1>contact section</h1>
</section>
);
});
function home({ innerrefs }) {
return (
<fragment>
<hero ref={innerrefs.heroref} />
<about ref={innerrefs.aboutref} />
<contact ref={innerrefs.contactref} />
</fragment>
);
}
export default home;
Source: stackoverflow.com
Related Query
- React scroll nav using useRef in seperate routes
- React scroll nav using useRef
- How to create seperate component just for routes using react router?
- Not able to scroll an element on click using useRef in React
- Using React Hooks To Update w/ Scroll
- How to keep scroll position using flatlist when navigating back in react native ?
- Google Crawler in Search Console can't found routes in React using Github Page
- Can I create alias routes using react router?
- How to make a React component fade in on scroll using IntersectionObserver, but only once?
- addEventListener('scroll') to scrollable <div /> using useRef - React
- React copy to clipboard using useRef hook
- Sizing one component by getting the width of another one using useRef hook in React
- synchronise scroll of two react components without using state and actions
- Protected Routes with AWS Amplify using React context
- React - Trigger form submit using useRef
- translate on Y using SectionList and header view creating empty space on scroll - react native
- Restore scroll position in React Hooks with useRef is shaky
- React custom Hook using useRef returns null for the first time the calling component Loads?
- How can I allow access to specific React Hash Routes using Spring Security?
- Routes not loading after using "npm run build" in React
- Best way to speed up a big React project by using "Snapshots" of critical routes (static renders)
- reactjs sticky nav bar to scroll to a div using window.scrollTo doesn't work
- React show routes if set up using react-router
- Using the same component for different Routes with React Router
- How to mock useRef using jest.mock and react testing library
- Using match in react routes
- how to test Routes in react using jest and react testing library
- Scroll to y location within react element with useRef
- Type for React useRef targeting a scroll
- How to set focus on custom input in ReactJS using useRef and react hooks?
More Query from same tag
- Is it good to use package.json file in react component file?
- Can't get componentDidUpdate() stop looping
- Convert const function code from JSX to TSX
- Uncaught TypeError: snap.data() is undefined
- How to make code changes show when using yalc
- Memory Leak on React App that uses RealTime Firebase DataBase
- Material UI autocomplete popper custom closes on click
- Sticky navbar with React Nextjs
- How do I solve a NetworkError when attempting to debug a React Native application?
- Pass a function through React Router
- Handling images in my react app in production
- Having some problem on using map() method on my react application
- How to validate numeric inputs in ReactJS
- shouldComponentUpdate + deepEqual and arrays
- Framer animation using react intersection observer. Need multiple animations but get only one
- 'Error: self signed certificate' with node+express application
- Leaflet never loads leaving the screen blank with no errors
- create-react-app in VS Code throwing unauthorized access on Windows
- Set nested item in object/array from array of keys
- Destructuring (spread operator) works in React JSX, but not outside?
- How to switch between 2 components on the same page?
- Uncaught TypeError: Cannot read properties of undefined (reading 'location')
- Why data not displaying in the react-bootstrap-table?
- material ui (mui) button have incorrect styling
- How to make rest api in to to display data in react js
- react-hook-form validation not working with custom fields array
- Add vendor prefixes for inline css in React for background Linear Gradient
- How can I access this.state of React component inside of a filter function?
- Redux in React App duplicating in store when it should not be
- Next.JS useRouter will only returns an empty object for a dynamic route