Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass props from page to components in Nextjs

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

like image 642
Filip Simin Avatar asked May 21 '20 14:05

Filip Simin


People also ask

How do I pass a prop to a component?

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.

How do I move props to pages in Nextjs?

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.

How do you pass data between components in Nextjs?

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.

Can I use getStaticProps in a component?

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).


1 Answers

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.

like image 65
Muhammad Ali Avatar answered Oct 18 '22 14:10

Muhammad Ali