Styled Components with bracket doesn’t work properly in Next.js
I’m using typescript, styled-components with Next.js
package.json
"dependencies": {
"@reduxjs/toolkit": "^1.6.2",
"babel-plugin-styled-components": "^2.0.2",
"next": "12.0.4",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-inlinesvg": "^2.3.0",
"react-redux": "^7.2.6",
"redux": "^4.1.2",
"redux-saga": "^1.1.3",
"styled-components": "^5.3.3"
},
"devDependencies": {
"@types/node": "^16.11.10",
"@types/react": "^17.0.37",
"@types/styled-components": "^5.1.15",
"eslint": "7.32.0",
"eslint-config-next": "12.0.4",
"typescript": "^4.5.2"
}
.babelrc
{
"presets": ["next/babel"],
"plugins": [
[
"babel-plugin-styled-components",
{
"ssr": true,
"displayName": true,
"preprocess": false
}
]
]
}
_document.tsx
import React from "react";
import Document, { Html, Head, Main, NextScript } from "next/document";
import { ServerStyleSheet } from "styled-components";
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();
}
}
render() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
but in a certain situation, like using Styled Components with bracket, and the components in the bracket were imported, styled-components cannot apply any of it.
(it can render the imported component, but cannot apply any additional styles)
RegisterForm.tsx
import React, { useState } from 'react';
import styled from 'styled-components';
import RoundButton from '../../components/common/RoundButton';
const RoundButtonWithMarginTop = styled(RoundButton)`
margin-top: 3.75rem;
`;
const RegisterForm = () => {
...
<RoundButtonWithMarginTop>Next</RoundButtonWithMarginTop>
...
}
components/common/index.tsx
export * from './Header';
export * from './Responsive';
export * from './RoundButton';
components/common/RoundButton.tsx
import React from 'react';
import styled from 'styled-components';
import palette from '../../lib/styles/palette';
const RoundButtonBlock = styled.button`
width: 100%;
background-color: ${palette.Gray[1]};
border-radius: 30px;
border: none;
font-size: 1.1em;
font-weight: 700;
height: 3rem;
cursor: pointer;
&:hover {
background-color: ${palette.Gray[0]};
}
`;
const RoundButton = ({ children }) => {
return (
<RoundButtonBlock>
{children}
</RoundButtonBlock>
);
};
export default RoundButton;
how button appears on the page
How can I solve this problem?
Please give me the solution.