Issue
I'm trying to render a landing page using getStaticProps
(Next.js) but it doesn't behave as expected. Here is my component:
import { GetStaticProps } from 'next'
const Brief = (props) => {
console.log(JSON.stringify(props)) // returns an empty object
return (
<>
{props[0]}
{props[1]}
{props[2]}
</>
)
}
export const getStaticProps: GetStaticProps = async (context) => {
const WhatIUse = <div className="WhatIUse">What I use</div>
const introduction = <div className="introduction">Introduction</div>
const ContactInfo = <div className="ContactInfo">Where to find me</div>
return {
props: [introduction, WhatIUse, ContactInfo]
}
}
export default Brief
The logging statement shows that props
is returned as an empty object, what could be the issue?
Solution
There are a couple of things wrong with that approach.
First, the variable props
returned in getStaticProps
must be an object containing values that are serializable as JSON. You're trying to pass an array which contains JSX elements (non-serializable).
Second, getStaticProps
is used to fetch data for pre-rendering, you're not meant to generate JSX there, that'll be done in the component itself.
Here's a practical example based on your initial code:
const Brief = (props) => {
console.log(props) // Will log props passed in `getStaticProps`
return (
<>
<div className="WhatIUse">{props.data[0]}</div>
<div className="introduction">{props.data[1]}</div>
<div className="ContactInfo">{props.data[2]}</div>
</>
)
}
export const getStaticProps: GetStaticProps = async (context) => {
const WhatIUse = 'What I use'
const introduction = 'Introduction'
const ContactInfo = 'Where to find me'
return {
props: {
data: [introduction, WhatIUse, ContactInfo]
}
}
}
export default Brief
Answered By - juliomalves
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.