Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to type a styled component without losing any prop with Typescript?

I'm new to styled components and I'd like to be able to type my styled components correctly so that when I pass props "vs code" I can autodetect all those props I have, not just the one in the theme or the ones I could put with an interface.

Would there be any way without using a HOC for it as I've seen in some other answer? Is it possible to get a general prop to use in all without having to be defining in each property of style this as in the example?

app.theme.ts

export const theme = {
  palette: {
    primaryColor: '#FF5018',
    secondaryColor: '#252729',
    tertiaryColor: '#1A1C1E',
    textColor: 'white',
  },
};

export type Theme = typeof theme;

navigation-bar.styled.component.ts

export const NavigationBarStyled = styled.div`
  grid-area: navigation-bar-item;
  padding-left: 2rem;
  display: flex;
  align-items: center;
  color: ${({ theme }) => theme.palette.primaryColor};
  background-color: ${({ theme }) => theme.palette.primaryColor};
`;

Thanks in advance, Best

like image 427
frangaliana Avatar asked Dec 17 '22 18:12

frangaliana


1 Answers

It could be solved as @Huy-Nguyen said but in practice, you lose properties on Styled Components or you have to define the same many times.

So the best option is this as the Styled-Components website says (to define a theme interface):

theme.ts

export default interface ThemeInterface {
  primaryColor: string;
  primaryColorInverted: string;
}

styled-components.ts

import * as styledComponents from "styled-components";

import ThemeInterface from "./theme";

const {
  default: styled,
  css,
  createGlobalStyle,
  keyframes,
  ThemeProvider
} = styledComponents as styledComponents.ThemedStyledComponentsModule<ThemeInterface>;

export { css, createGlobalStyle, keyframes, ThemeProvider };
export default styled;

And then, you use that:

import styled from 'app/styled-components';

// theme is now fully typed
const Title = styled.h1`
  color: ${props => props.theme.primaryColor};
`;

Just pass the link: https://www.styled-components.com/docs/api#define-a-theme-interface

Thank you so much for all.

like image 82
frangaliana Avatar answered Dec 28 '22 17:12

frangaliana