In this sample code below: It is React
and Next.js
import App, { Container} from "next/app";
import React from "react";
class MyApp extends App{
render() {
const { Component } = this.props;
return (
<Container>
<p>Hey I am on every page</p>
<Component/>
</Container>
)
}
}
export default MyApp;
My question is about this line:
const { Component } = this.props;
My questions: How is this working? This is the highest page level I have. So who is passing this.props
to it? Also what kind of syntax is that? Why it called Components
? Could he call it something else?
Your MyApp
component extends a component named App, which is an internal Next react component. The reason you'd want to extend App
is if you're calling getInitialProps
before each page is loaded. You can think of App as a HOC (higher order component) that calls getInitialProps
in MyApp
first, then other Next methods within a page, like: getInitialProps
, getServerSideProps
, getStaticProps
, getStaticPaths
second.
This creates a render-blocking scenario where MyApp.getInitialProps
can block page-level methods from being executed until it has been resolved.
In your case, you don't even need to extend App since you're not calling getInitialProps, and instead, you can just use a pure function (or remove _app.js
completely if you don't need to include metadata or wrap each page
with some sort of layout component):
function MyApp({ Component, pageProps }) {
return (
<Component {...pageProps} />
);
}
export default MyApp;
All subsequent pages
(like /pages/example.js
) will be passed to this MyApp
component as the named Component
prop while any props returned from one the methods mentioned above will be passed to MyApp as the named pageProps
prop.
You can kind of think of App
(next/app) like this:
import React, { Component } from "react";
import MyApp from "../_app.js"; // custom _app page
import Example from "../example.js"; // a page component
class App extends Component {
static async getInitialProps(ctx) {
const { pageProps } = await MyApp.getInitialProps(ctx);
return { pageProps }; // this.props.pageProps
};
render() {
return <MyApp Component={Example} pageProps={this.props.pageProps} />
}
}
--
On a side note, the Container
component has been deprecated since v9.0.4
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments