NextJS integrates Styled Components
Open the NextJS project created in the previous article and add the following dependencies: NPM install babel-plugin-styled- Components –save-dev NPM install Styled – Components –save
1: touch. Babelrc // Add the Babel configuration file as follows:
{
"presets": ["next/babel"],
"plugins": [["styled-components", { "ssr": true }]]
}
Copy the code
2: Open pages/indes.js. The replacement code is as follows
import styled from 'styled-components'
const Title = styled.h1`
font-size: 50px;
color: ${({ theme }) => theme.colors.primary};
`
export default function Home() {
return <Title>My page</Title>
}
Copy the code
3: pages/_app.js, the replacement code is as follows
import { createGlobalStyle, ThemeProvider } from 'styled-components' const GlobalStyle = createGlobalStyle` body { margin: 0; padding: 0; box-sizing: border-box; } ` const theme = { colors: { primary: '#0070f3', }, } export default function App({ Component, pageProps }) { return ( <> <GlobalStyle /> <ThemeProvider theme={theme}> <Component {... pageProps} /> </ThemeProvider> </> ) }Copy the code
4: pages/_document.js, the replacement code is as follows
import Document from 'next/document' import { ServerStyleSheet } from 'styled-components' export default class MyDocument extends Document { static async getInitialProps(ctx) { const sheet = new ServerStyleSheet() const originalRenderPage = ctx.renderPage try { ctx.renderPage = () => originalRenderPage({ enhanceApp: (App) => (props) => sheet.collectStyles(<App {... props} />), }) const initialProps = await Document.getInitialProps(ctx) return { ... initialProps, styles: ( <> {initialProps.styles} {sheet.getStyleElement()} </> ), } } finally { sheet.seal() } } }Copy the code