TypeScript newbie here. I have a below component using styled-components
that I would like to convert to TypeScript
.
import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
const propTypes = {
name: PropTypes.string.isRequired // https://material.io/tools/icons/?style=baseline
}
const Icon = styled(({name, className, ...props}) => <i className={`material-icons ${className}`} {...props}>{name}</i>)`
font-size: ${props => props.theme.sizeLarger};
`
Icon.propTypes = propTypes
export default Icon
I know I can replace my propTypes
with an interface
interface Props {
name: string
}
However, TypeScript complains that I leave className
undeclared. The thing is, I would ideally like to use the interface
as a sort of spec for props that a developer can provide, without having to declare props like className
or theme
which are injected by libraries like styled-components
.
How do I properly convert this component to TypeScript?
In projects where you have a large codebase, using plain CSS can become time-intensive and tiring. That's where styled-components comes in. In this tutorial, we'll show you how to build and style a TypeScript app using styled-components. You can access the images required for this demo in my GitHub repository.
Styled components are a good choice for building a UI library since everything can be in one file and easily be exported and reused. If you prefer writing pure CSS, use CSS modules. You can have separate CSS files, and it locally scopes styles by default.
Angular applications are styled with standard CSS. That means you can apply everything you know about CSS stylesheets, selectors, rules, and media queries directly to Angular applications. Additionally, Angular can bundle component styles with components, enabling a more modular design than regular stylesheets.
Change the default styled engine By default, MUI components come with Emotion as their style engine. If, however, you would like to use styled-components , you can configure your app by following the styled engine guide or starting with one of the example projects: Create React App with styled-components.
import React from "react";
import styled from "styled-components";
interface Props {
name: string;
className?: string;
}
const NonStyledIcon: React.SFC<Props> = ({ name, className, ...props }) => (
<i className={`material-icons ${className}`} {...props}>
{name}
</i>
);
const Icon = styled(NonStyledIcon)`
font-size: ${props => props.theme.sizeLarger};
`;
export default Icon;
As per the styled-components TypeScript docs: when defining a component you will need to mark className as optional in your Props interface
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With