Its giving this error "Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead." Please help.
export default function PostScreen() {
const data = 'Hello';
return (
<>
<div>
<span>Create Post</span>
<Link
href={{
pathname: '/details',
query: data,
}}
>
<a>Click me</a>
</Link>
</div>
</>
);
}
// Another page
function Details(){
const router = useRouter();
const data = router.query;
return (
<div>
<div>
<div>
<strong>Username:</strong> {data}
</div>
</div>
</div>
);
}
CodePudding user response:
query
in href
accepts an object with key value pairs. If you pass string
, it will convert the variable's value of the string to key
and its value will be empty;
If you do a console.log(data)
on the /details
page, you get the following:
{ Hello: '' }
React
doesn't support rendering JS objects in the JSX. Hence, you see that error.
So, to solve your problem, you can give some key to the data and use that key in /details
page to get your data.
For example:
export default function PostScreen() {
const data = 'Hello';
return (
<div>
<span>Create Post</span>
<Link
href={{
pathname: '/details',
query: { message: data },
}}
>
<a>Click me</a>
</Link>
</div>
);
}
// "/details" page
function Details(){
const router = useRouter();
const data = (router.query ?? {}).message;
return (
<div>
<div>
<div>
<strong>Username:</strong> {data}
</div>
</div>
</div>
);
}
CodePudding user response:
Route.query is a object. you should unpack it first, like:
const {id} = data
Then pass id to the HTML