Reputation: 15498
I have a Link component that I'm using and want to pass a JavaScript object to the new page I'm linking to. It seems that I can pass primitives, but not objects.
That is, I want to do something like this below but I get an empty string associated with sessionData (session.id and session.sessionSlug work).
<Link
href={{
pathname: "/session", query:
{
sessionSlug: this.props.session.sessionSlug,
sessionId: this.props.session.id,
sessionData: this.props.session
}
}}
as={`session/${this.props.session.sessionSlug}`}>
<a>{this.props.session.title}</a>
</Link>
https://nextjs.org/docs/#with-link
Upvotes: 4
Views: 11812
Reputation: 4230
I think you can try to JSON.stringify
the object and then JSON.parse
it back
Example
pages/index.js
import Link from 'next/link';
export default () => {
const object = {
key1: 'value1',
key2: 'value2'
};
return (
<Link href={{ pathname: '/about', query: { object: JSON.stringify(object) } }}>
<a>here</a>
</Link>
);
};
pages/about.js
import { withRouter } from 'next/router';
function About({ router: { query } }) {
const object = JSON.parse(query.object);
return (
<div>
about {object.key1} | {object.key2}
</div>
);
}
export default withRouter(About);
Hope this helps!
Upvotes: 9