Reputation: 87
I have this ./pages/_app.js
from the official docs:
import App, { Container } from 'next/app'
class MyApp extends App {
static async getInitialProps({ Component, ctx }) {
let pageProps = {}
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}
return { pageProps }
}
render () {
const { Component, pageProps } = this.props
return (
<Container>
<Component {...pageProps} />
</Container>
)
}
}
export default MyApp
I want to pass state from MyApp to every page it renders, but can't figure how. I tried this:
const childProps = {
...
}
<Container>
<Component {...childProps} />
</Container>
and got an error:
React.Children.only expected to receive a single React element child.
Upvotes: 1
Views: 5553
Reputation: 415
pass what you want just as you pass usual props
<Component whatyouwant={propsyouwant} />
For example: this is how I passed MobileDetect props to every component in my app:
class MyApp extends App {
static async getInitialProps({ Component, router, ctx }) {
let pageProps = {}
const { req } = ctx
var MobileDetect = require('mobile-detect')
const md = new MobileDetect(req ? req.headers['user-agent'] : "")
const phone = md.phone()
const tablet = md.tablet()
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}
return { pageProps,
phone: phone,
tablet: tablet }
}
render () {
const {Component, pageProps, phone, tablet} = this.props
return (
<Container>
<Provider store={reduxStore}>
<Nav />
<Component {...pageProps} phone={phone} tablet={tablet} />
<Footer />
</Provider>
</Container>
)
}
}
export default withReduxStore(MyApp)
Upvotes: 1
Reputation: 87
The culprit was
<Link>
<Icon />
text
</Link>
in the rendered page (not _app.js
).
The Link had two children (remnants of react-router Link) instead of one.
Upvotes: 1