Using styled-jsx in pages/_app.js causes a TypeError: Cannot read property 'className' of undefined render error.
Steps to reproduce the behavior, please provide code snippets or a repository:
pages/_app.js file.<style jsx> styles to it.JSX in pages/_app.js can be styled using styled-jsx without a render error.
N/A.
N/A.
I just tried this and didn't see any errors. Can you paste your _app.js code here?
Although it is recommend to avoid having styling in the _app.js and instead wrap <Component {...pageProps} /> in some Layout component where you'd add global styles.
For example, the render method of _app.js in my projects usually looks like this:
return (
<Container>
<PageWrapper>
<Component {...pageProps} />
</PageWrapper>
</Container>
);
and inside the <PageWrapper> component I add all components and styles that need to load on every page.
Just tried and it seems to be working fine:
import React from 'react'
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>
<div className="test">
<Component {...pageProps} />
<style jsx>{`
.test {
background: red;
}
`}</style>
</div>
</Container>
)
}
}
export default MyApp
I worked out what I was doing wrong.
In a nutshell, with App.getInitialProps something like this:
static async getInitialProps({ ctx, Component }) {
const props = {}
if (Component.getInitialProps)
props.pageProps = await Component.getInitialProps(ctx)
// Done this way so other props can be added here…
return props
}
Here is the fix I needed in render():
const {
Component,
- pageProps,
+ pageProps = {},
graphql
} = this.props
So that this could work:
<Component {...pageProps} />
For some reason this bug only revealed itself when adding <style jsx> to the App.
Sorry for any time wasted!
got it
Most helpful comment
I worked out what I was doing wrong.
In a nutshell, with
App.getInitialPropssomething like this:Here is the fix I needed in
render():So that this could work:
For some reason this bug only revealed itself when adding
<style jsx>to theApp.Sorry for any time wasted!