40
loading...
This website collects cookies to deliver better user experience
@types/styled-components
but it doesn't seem to work very well with custom themes. This post will help you with that.Styled-Components-Typescript: Property 'backgroundColor' does not exist on type 'DefaultTheme'
, which is a very common error if you're using a custom theme with Typescript and apparently they don't maintain the types.styled.d.ts
)// import original module declarations
import "styled-components";
// and extend them!
declare module "styled-components" {
export interface DefaultTheme {
borderRadius: string;
colors: {
main: string;
secondary: string;
};
}
}
// source: https://styled-components.com/docs/api#create-a-declarations-file
// myTheme.ts
import { DefaultTheme } from "styled-components";
const myTheme: DefaultTheme = {
borderRadius: "5px",
colors: {
main: "cyan",
secondary: "magenta",
},
};
export { myTheme };
// source: https://styled-components.com/docs/api#create-a-theme
styled.d.ts
)// myTheme.ts
export const myTheme = {
borderRadius: "5px",
colors: {
main: "cyan",
secondary: "magenta",
},
};
myTheme
) with the DefaultTheme.// styled.d.ts
import "styled-components";
import { myTheme } from "./theme";
declare module "styled-components" {
type MyTheme = typeof myTheme;
interface DefaultTheme extends MyTheme {}
}
App.tsx
or _app.jsx
in Next.js. In that file you just need to create a ThemeProvider
and pass your theme to it. Something like this:// With React.js
import { ThemeProvider } from "styled-components";
import { myTheme } from "./theme";
function App() {
return (
<ThemeProvider theme={myTheme}>
<h1>Hello World!</h1>
</ThemeProvider>
);
}
export default App;
_app.tsx
file they give you.// With Next.js
import { ThemeProvider } from "styled-components";
import type { AppProps } from "next/app";
import { myTheme } from "./theme";
function MyApp({ Component, pageProps }: AppProps) {
return (
<ThemeProvider theme={myTheme}>
<Component {...pageProps} />
</ThemeProvider>
);
}
// Box.tsx
import styled from "styled-components";
const BoxContainer = styled.div`
display: flex;
border-radius: ${(props) => props.theme.borderRadius};
color: ${(props) => props.theme.colors.main};
background-color: ${(props) => props.theme.colors.secondary};
`;
const Box = () => <BoxContainer>Hello World!</BoxContainer>;
// Box.tsx
import styled from "styled-components";
const BoxContainer = styled.div`
display: flex;
border-radius: ${({ theme }) => theme.borderRadius};
color: ${({ theme }) => theme.colors.main};
background-color: ${({ theme }) => theme.colors.secondary};
`;
const Box = () => <BoxContainer>Hello World!</BoxContainer>;