Technologies:
Tolerim
a month ago
How can I assign custom props to a createGlobalStyle component in TypeScript using styled-components?
I am utilizing styled-components and TypeScript to construct a GlobalStyle component. It is my intention to pass a custom prop named cssContent to the component. However, I am encountering a type error. To generate the cssContent string, I need a function which takes arguments. This function is necessary.
Here is the code:
, any, any>> & Readonly<...>'.
```
How can I resolve this type error and properly pass the custom cssContent prop to my GlobalStyle component? Thank you.
interface GlobalStyleProps {
cssContent: string;
}
const GlobalStyle = createGlobalStyle`
${(props) => props.cssContent}
`;
export const generateGlobalStyle = (): string => {
return `
:root {
}
//my css code...
`;
};
function App() {
const cssContent = generateGlobalStyle();
return (
<>
Hello World
>
);
}
However, I'm getting the following error:
```
Type '{ cssContent: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributesAnswers(2)
Vogi
a month ago
Verified Answer
The error you are seeing is due to the fact that the createGlobalStyle function from styled-components expects a type parameter that extends the GlobalStyleProps interface. However, in your code, you are not extending the GlobalStyleProps interface. To fix this error, you can extend the GlobalStyleProps interface in your createGlobalStyle function like this:
const GlobalStyle = createGlobalStyle<GlobalStyleProps>`
${(props: GlobalStyleProps) => props.cssContent}
`;
This should resolve the type error you are seeing. Let me know if you have any other questions!
Sources
reactjs - Typescript with Styled-Component Error: Type ...Typescript error using styled-components - Stack OverflowHow To Fix Styled Components Prop Types Issue In TypescriptTolerim
a month ago
To resolve this type error, you need to add the cssContent prop to the ThemedGlobalStyledClassProps interface. Here's an updated version of your code:
import { ThemedGlobalStyledClassProps, DefaultTheme, createGlobalStyle } from "styled-components";
interface GlobalStyleProps {
cssContent: string;
}
const GlobalStyle = createGlobalStyle<ThemedGlobalStyledClassProps<GlobalStyleProps, DefaultTheme>>`
${(props) => props.cssContent}
`;
export const generateGlobalStyle = (): string => {
return `
:root {
}
//my css code...
`;
};
function App() {
const cssContent = generateGlobalStyle();
return (
<>
<GlobalStyle cssContent={cssContent} />
<h1>Hello World</h1>
</>
);
}
In this code, we have imported ThemedGlobalStyledClassProps and DefaultTheme from styled-components. We have also modified the definition of the GlobalStyle component to use ThemedGlobalStyledClassProps instead of GlobalStyleProps. This ensures that the cssContent prop is recognized by styled-components.
Now, you should be able to pass the custom cssContent prop to your GlobalStyle component without encountering a type error.