Using TypeScript with Styled Components
Styled-components, what are they? The result of thinking about how to enhance the CSS for component systems styling in React. A JavaScript subset, it mainly provides static classes, interfaces, as well as static typing.
One of the most noticeable TypeScript pros is enabling IDEs to provide a richer environment that could see common errors in code typing. It streamlines Java code, which makes reading and debugging so much easier.
Use TypeScript with Styled Components
It’s great to use styled-components with React, as well as React native. However, it truly shines when using it with VS Code, getting suggestions about the code and errors when writing an error. The components help keep problems regarding the separation of styling and architecture, which makes for a more readable code.
In addition, should there be components relying on JavaScript, the components provide control over the states, and then back to CSS, and not using many conditional class names instead. When transitioning most projects to include TypeScript, some things would feel perfect. Consider checking them out.
1. Types Installation
Styled components do not ship with types. Rather, you need to install it from the repository called the Definitely Typed.
npm i --save-dev @types/styled-components
2. Customized props
Using a CSS in a JavaScript solution has one particular major advantage, and this the ability of passing customized props on the runtime, as well as accordingly adapting CSS.
const HeaderTitle = styled.h1<{ isActive: boolean }>` color: ${props=>(props.isActive ? 'green' : 'red' )} `;
Similar to JSX elements, the generic type could be passed after the component with <>. Now, what you have is a typed styled-component, and thus will become a static element error if unable to pass the active prop.
To extend the component, you can use it like this:
import Title from './Title' const HeaderTitle = styled(Title)<{ isActive: boolean }>` color: ${props=>(props.isActive ? 'green' : 'red' )} `;
Keep in mind however that active as a prop is passed to the Title component even if not explicitly stated so. Later, if someone adds an optional prop to the component, this could be a concern. You can nonetheless refactor to avoid this, such as:
const HeaderTitle = styled(({ isActive, ...rest }) => <Title {...rest} />)<{ isActive: boolean; }>` color: ${props => (props.isActive ? 'green' : 'red')}; `;
This syntax however obviously is more intricate, and builds additional component. If the mess is worth uncovering an accidental prop, it would be your decision.
3. Typing a Theme
With the help of the ThemeProvider, Styled Components could specify a theme. The autocomplete form itself form the theme object is worth doing even if you steer away from everything else.
The first thing to do is to build a declarations file. For instance, we shall call it styled.d.ts.
// import original module declarations import 'styled-components'; // and extend them! declare module 'styled-components' { export interface DefaultTheme { fontSize:{ body: string; h1: string; h2: string; h3: string; h4: string; h5: string; h6: string; }, colors: { main: string; secondary: string; }; } }
Typing the theme manually like this is hard however, mainly due to the fact that every time you add or remove something form the theme object, you have to edit a couple of files. Rather, consider doing this:
import {} from 'styled-components'; import myTheme from '../custom-theme'; declare module 'styled-components' { type Theme = typeof myTheme; export interface DefaultTheme extends Theme {} }
We make use of the type inference of TypeScript here for the theme object to do it.
4. Using the CSS Prop
In the Styled Components documentation, there are a couple of CSS functions. Here specifically is the attribute of CSS that could be utilized on an element when a Babel plugin is enabled.
<div css={` display: block; `} > ... </div>
Unfortunately, TypeScript does not know about this CSS property, and makes an error.
To resolve this, consider the following styled.d.ts:
import {} from 'styled-components'; import { CSSProp } from 'styled-components'; declare module 'react' { interface Attributes { css?: CSSProp | CSSObject; } }
5. The Media Templates
Specifying media queries from documentation has an easy way. However, while the syntax is user-friendly, the implementation is difficult to reason for TypeScript, and for new users too as it happens. Consider the following seamless option:
const customMediaQuery = (maxWidth: number) => `@media (max-width: ${maxWidth}px)`; const media = { custom: customMediaQuery, desktop: customMediaQuery(992), tablet: customMediaQuery(768), phone: customMediaQuery(576), }; const ContentBlock = styled.div` width: 4em; height: 4em; background: white; /* Now we have our methods of raw queries */ ${media.desktop} { background: green; } ${media.tablet} { background: yellow; } ${media.phone} { background: blue; } `; render(<ContentBlock />);
The Pros of TypeScript
- Helps deal with growing teams
- Code scalability
- Compliance to ES-next
- Awesome tooling and community effort
- Types boost agility when refactoring. It’s also better for a compiler to catch errors than having things fail during runtime
- Have a proven ability of enhancing the quality and understandability of code.
- With typing, it provides a taste of the future of JavaScript
- One of the best forms of documentation.
- With auto-injection libraries combined, the code-base is truly predictable and maintainable.
- The dependency injection opens up a lot of opportunities for cool testing, and make sure that the APIs are controller-based.
- The Dependency Injections makes for easy testing.
- Supports change and innovation, with safety measures that ensure it won’t entirely go the wrong way.
- Helps in the implementation of sturdy design patterns into a language that does not really support it.
- Make more readable code, helping developers remember what every code piece is supposed to do fast.
- Could compile down to a JavaScript version, which runs on all browsers.
- The code completion IntelliSense provides active hints that a code is being added.
- Very easily write pure TypeScript object-oriented code with less knowledge.
- The static typing feature detects a bug or bugs as a developer is writing the scripts. This enables a developer to write more sturdy code, maintain it, which result in cleaner, better code.
- TypeScript tools make refactoring faster and easier.
Why Styled Components?
1. Makes less bulky components. There would be plenty of heavy lifting done via the CSS for injecting styling towards a component that’s user-centered. Majority of the methods id render components end up with style objects, which clutter and splits the CSS into two, making the code parsing process difficult. Styled components however keep the element architecture and styling separated, and make more readable components.
2. CSS Function. Props could be used to render CSS conditionally, meaning that there’s no need to render conditional classes names that are props-based. This minimizes components clutter, and maintaining a separation of issues between JavaScript and CSS.
3. ThemeProvider. Severing as the wrapper, it injects props into all the child components. It’s significantly useful when creating a ‘configuration’ page, which is a duplicate page essentially, letting users perform customizations to specific stylistic elements, such as color in particular.
4. Test. Testing of the styled components is painless through building class names that are consistent. Moreover, it also enables asserting certain CSS rules, which could be relevant to the app’s integrity.
Conclusion
Styled-components overall, have made creating apps with TypeScript more enjoyable. The styles are a neat approach to scoping styles. TypeScript could be leveraged to have a strong-typing in props passed to the styled components.
The styled components have over 5.7 million downloads per month from npm, more than 27.8 GitHub stars, as well as hundreds of open source contributors, thus it’s here to stay.
Author Profile:
V K Chaudhary working as a project manager in a software development company Tatvasoft.com. He is a technical geek and also managing some online campaigns for his company.