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?
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()
componentDidMount() {
if (typeof window === 'undefined') {
return;
}
this.setState(() => ({ playerName: this.props.location.state.playerName }));
}
In render()
render() {
return <div>{this.state.playerName}</div>;
}
credit to this thread, How to get previous url in react gatsby
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With