I am passing data from one page to another in gatsby. First page code:
let state = {book: book, src: src}
return (
<div className="book__holder">
<Link to="/pdf/" state={state}>
<Card
hoverable
style={{ width: 240 }}
cover={<img alt={book}
src={url}
/>}
>
<Meta
title={book}
description={faculty+" "+year+"-"+part}
/>
</Card>
</Link>
</div>
This data is used in pdf page as:
const PDFPage = props =>{
return (
<React.Fragment>
<SEO title={props.location.state.book} />
<NavBar></NavBar>
<Embed src={props.location.state.src} type="application/pdf">
</Embed>
</React.Fragment>
)}
export default PDFPage
Everything is fine when using gatsby develop but when i use gatsby build it throws following error:
error Building static HTML for pages failed
See our docs page on debugging HTML builds for help https://gatsby.app
/debug-html
11 | return (
12 | <React.Fragment>
> 13 | <SEO title={props.location.state.book} keywords={[`gatsby`,
`application`, `react`]} />
| ^
14 | <NavBar></NavBar>
15 | <Embed src={props.location.state.src} type="application/pdf">
</Embed>
16 |
WebpackError: TypeError: Cannot read property 'book' of undefined
- pdf.js:13 PDFPage
lib/src/pages/pdf.js:13:38
Can anyone help me please?
2
Answers
Passing Props to Link targets
While the following demo is not actually using gatsby, it is using reach router (and gatsby uses reach router under the hood).
Stackblitz
Gatsby will throw error during production build, since location is not available during server-side rendering.
One way to make sure the build doesn’t throw an error is to:
In componentDidMount()
In render()
credit to this thread, How to get previous url in react gatsby