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>
}
}
getInitialProps enables server-side rendering in a page and allows you to do initial data population, it means sending the page with the data already populated from the server. This is especially useful for SEO. getInitialProps will disable Automatic Static Optimization.
Addition of getServerSideProp and getServerSideProp is greatly desirable, since getInitialProps will be deprecated and most likely deleted from next. js .
getServerSideProps does not work in _app. js . see docs. you could use the older getInitialProps in your custom app component but then the automatic static optimisation is disabled, which is something Next.
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.
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