I want to pass my props from a page to all other components. I have a dynamic route set up like this.
-pages
-[tv]
-index.js
-category
-index.js
...
So the rout looks like this: pages/[tv]/category/...
My index.js, child of folder [tv], page code.
const Home = props => {
const router = useRouter()
const { tv } = router.query
console.log(tv) //Value that i want to pass as props to other components.
So i want to pass value of tv to other components as props. Hope my question is not too vague.
Thank you
To pass props, add them to the JSX, just like you would with HTML attributes. To read props, use the function Avatar({ person, size }) destructuring syntax. You can specify a default value like size = 100 , which is used for missing and undefined props.
There is no way to pass data between pages with Next's router. You would have to either use query strings as you mentioned, sessionStorage, or a state management option like Redux or React's Context API. You could then put that in your pages/_app.
You need to update the state after your data returns so that the component can rerender with the fetched data, using something like setTrack(track) . Then in your component you can pass the data from the state.
If you want to fetch component-specific data at the component level, you can use a mechanism similar to page-level data fetching, by implementing and exporting getStaticProps for static generation (SG), or getServerSideProps for server-side rendering (SSR).
If those components are rendered in Home
component, you can just pass tv
as prop:
const SomeComponent = props => {
const { query } = useRouter()
const { tv } = query
// ...
}
const Home = props => {
// ...
return (
<SomeComponent />
)
};
If you don't want prop drilling then you can just use the useRouter
hook.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With