When I use the state
with the gatsby component Link
that work when I do test with gatsby develop
but failded with gatsby build
with an error about undefined
stuff. The error message show by the terminal is WebpackError: TypeError: Cannot read property 'info' of undefined
I try to check for undefined
by two differents ways but that's don't work. I cannot figure what I must do to solve that's problem.
first test :
if (!location.state.info) {
return null
} else
second test
if (typeof location.state.info === `undefined`) {
return null
} else
index page
import React from "react"
import { Link } from "gatsby"
import Layout from "../components/layout"
const IndexPage = () => (
<Layout>
<Link to="/page_test/" state={{ info: "test" }}>
Test
</Link>
</Layout>
)
export default IndexPage
page
import React from "react"
import { Link } from "gatsby"
const TestPage = ({ location }) => {
return <div>{location.state.info}</div>
}
export default TestPage
What's undefined
is location.state
, not the info
state itself. Changing your condition your code should work.
if (typeof location.state === `undefined`) {}
Here's some approach (same idea) using destructuring:
const TestPage = ({ location }) => {
const { state = {} } = location
const { info } = state
return info ? (
<div>{info}</div>
) : (
<div>Other content</div>
)
}
export default TestPage
Basically, with the destructuring, you are simplifying stuff. It's what you are using in ({ location })
. By default, props
are passed through pages and components in React so ({ location })
equals to (props)
and then props.location
. It's just a way of entering the nested properties of the object.
In the same way, once you have props.location
(or location
if destructured in props
), you can:
const { state = {} } = location //equals to location.state
In the case above, you are destructuring plus setting a default value to empty ({}
) if there's no state
nested object in location
.
In the same way:
const { info } = state //equals to state.info
If state
is empty due to the previous destructuring, info will be empty as well, if not, it will take the value of state.info
. So your return method can be a boolean condition such:
return info ? (
<div>{info}</div>
) : (
<div>Other content</div>
)
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