How to make extracting components in typescript less cumbersome?

So let's say for example I have a button styling that i'd like to use across most of my app. The recommended tailwind approach is to extract it to a component. However, doing this repeatedly can get quite cumbersome since I have to type every single prop. Is there anyway to infer or automatically create these prop types? I'm using webstorm and they have a extract to react component button, but it will just slap a :any on the props. Has anyone found a way to make the process of doing this more streamlined?
6 Replies
Lopen
Lopen17mo ago
Have you heard of shadcdn?
Lopen
Lopen17mo ago
shadcn/ui
shadcn/ui
Beautifully designed components built with Radix UI and Tailwind CSS.
Lopen
Lopen17mo ago
I think this answers your question You can get a lot of inspiration from it
glaydur
glaydur17mo ago
Generally you'd only type the props that you need. Say for example creating a NewButton component that accepts a label: string and onClick: () => void props. and just have that as your props. There are cases though that you'd want to spread the props of a native html button (or extend a button component from some component library). In VSCode, I would just hover over the component and it'll actually give you type for that component's props which you can just copy and paste. (see image for example)
Dylz
DylzOP17mo ago
gotcha, thanks guys. I just wish there was a way I could highlight some jsx on my component and click a button and it would spit out a properly typed component based on what i extracted but sounds like that isn't possible
bakdaddy
bakdaddy17mo ago
you cound possibly define props like this
//any html element instead of 'div'
type Props = React.ComponentProps<'div'>
//any html element instead of 'div'
type Props = React.ComponentProps<'div'>
just choose an html tag as Element and then you could customly choose things like this
const Card = ({ children, className, ...props }: DivProps) => {
return (
<div className={`card shadow-md border ${className}`} {...props}>
{children}
</div>
);
};
const Card = ({ children, className, ...props }: DivProps) => {
return (
<div className={`card shadow-md border ${className}`} {...props}>
{children}
</div>
);
};
so something like
type ButtonProps = React.ComponentProps<'button'>

export const Button = ({className, ...props}: ButtonProps) => {
return <button className={`p-2 rounded bg-red ${className}`} {...props}></button>
}
type ButtonProps = React.ComponentProps<'button'>

export const Button = ({className, ...props}: ButtonProps) => {
return <button className={`p-2 rounded bg-red ${className}`} {...props}></button>
}
Want results from more Discord servers?
Add your server