Reputation: 2485
what is this really do ?
pageProps = await Component.getInitialProps(ctx)
it looks "pageProps" this is just an empty object
import App, {Container} from 'next/app'
import React from 'react'
export default class MyApp extends App {
static async getInitialProps ({ Component, router, ctx }) {
let pageProps = {}
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}
return {pageProps}
}
render () {
const {Component, pageProps} = this.props
return <Container>
<Component {...pageProps} />
</Container>
}
}
Upvotes: 11
Views: 21588
Reputation: 14268
getInitialProps
allows you to call out to get the props that you would like the component to have when rendered on the server.
For instance, I might need to display the current weather and I want Google to index my pages with that information for SEO purposes.
To achieve that, you'd do something like this:
import React from 'react'
import 'isomorphic-fetch'
const HomePage = (props) => (
<div>
Weather today is: {weather}
</div>
)
HomePage.getInitialProps = async ({ req }) => {
const res = await fetch('https://my.weather.api/london/today')
const json = await res.json()
return { weather: json.today }
}
export default HomePage
The line pageProps = await Component.getInitialProps(ctx)
calls that initial function so that the HomePage
component is instantiated with the initial props that result from that call to the weather API.
Upvotes: 12