Issue
how can I get type hints for extended styled-component props in vscode? I don't talk about style's props but about component's props.
When I extend my own component with styled(), type hint for props work perfectly. But when I use third-party component inside styled(), vscode don't give me any props hint.
import React from "react";
import styled from "styled-components";
import NumberFormat from "react-number-format";
const InputElement = styled(NumberFormat)`
border: 5px solid #eddcc7;
font-size: 1.5em;
max-width: 850px;
width: 100%;
text-align: center;
padding: .75em;
font-weight: 500;
line-height: 1.5;
`
const Input: React.FC = () => {
return (
// Get type hints for below extended styled component
<InputElement />
);
};
export default Input;
What I do wrong and what can I do correct?
Thanks for help 😅
Solution
Seems like the problem is that the styled-component is not picking up properly props from the react-number-format library. The issue might be that react-number-format's default exported component's props, NumberFormatProps contain the [key: string]: any field, which causes styled-component to break its type inference.
The issue can be resolved if you instead make a type from the NumberFormat component, which will instead have the NumberFormatPropsBase props.
Here's an example:
import styled from "styled-components";
import NumberFormat, { NumberFormatPropsBase } from "react-number-format";
const InputElement = styled<React.ComponentType<NumberFormatPropsBase>>(
NumberFormat
)`
border: 5px solid #eddcc7;
font-size: 1.5em;
max-width: 850px;
width: 100%;
text-align: center;
padding: 0.75em;
font-weight: 500;
line-height: 1.5;
`;
If you're using the NumberFormat styled component in multiple places, I also recommend you to extract to a different file:
MyNumberFormat.tsx
import NumberFormat, { NumberFormatPropsBase } from "react-number-format";
export default NumberFormat as React.ComponentType<NumberFormatPropsBase>;
export * from "react-number-format";
And then use it from there:
import NumberFormat from "./MyNumberFormat";
const InputElement = styled(NumberFormat)`
border: 5px solid #eddcc7;
font-size: 1.5em;
max-width: 850px;
width: 100%;
text-align: center;
padding: 0.75em;
font-weight: 500;
line-height: 1.5;
`;
Answered By - Kapobajza
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.