Type error while passing query string as props to arbitrery component in Next.js 12.4

33 Views Asked by At

I newbie in Next.js and I've just started learnig routing and query params. I wanted to pass query params down as props to a component to sort my list based on that params. However, when I got my query string through below code

interface Props {
  searchParams: { sortOrder: string };
}

const UsersPage = ({ searchParams: { sortOrder } }: Props) => {
  return (...)

and passed it through below code

      <UsersTable sortOrder={sortOrder}/>

I catch this error

Type '{ sortOrder: string; }' is not assignable to type 'IntrinsicAttributes'. Property 'sortOrder' does not exist on type 'IntrinsicAttributes'.

I caught this error on consol Error: Cannot read properties of undefined (reading 'sortOrder') So I tried to set the type of queryParams to string or undefined. But it didn't work.

2

There are 2 best solutions below

0
Alireza On

To resolve this, I simply defined the Props interface within the component and made sure to pass props as a parameter to the component function. This ensured that the props were correctly typed and accessible within the component.

I wanted to share this solution with you all in case anyone else runs into a similar issue in their code. Remember, properly defining props interfaces and passing props as parameters is essential for type safety and preventing type errors in your React components.

Happy coding!

0
Paul M. On

This should work: <UsersTable searchParams={{ sortOrder }} />