How to turn any HTML element into a React component with TypeScript

🚀 React + TypeScript Tip 🚀 Want to turn any HTML element into a clean, reusable React component? Here's how you can do it with TypeScript while keeping your code flexible and conflict-free!. Why does this work so well? ✅ 𝗖𝘂𝘀𝘁𝗼𝗺 𝗣𝗿𝗼𝗽𝘀: You define exactly what you need (e.g., variant, text) while inheriting all standard HTML attributes via React.ComponentProps. ✅ 𝗖𝗼𝗻𝗳𝗹𝗶𝗰𝘁-𝗙𝗿𝗲𝗲: By omitting className, you avoid prop conflicts and retain full styling control. ️✅ 𝗥𝗲𝘂𝘀𝗮𝗯𝗶𝗹𝗶𝘁𝘆: This pattern makes your components modular, type-safe, and ready to scale. We use 𝗢𝗺𝗶𝘁 TypeScript utility to exclude unnecessary/conflicting props and combine custom logic with inherited HTML attributes.💪 𝗣𝗦: → React.ComponentProps<"button"> includes all default attributes of button → React.ComponentProps<"input"> includes all default attributes of the input element and so on. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #nextjs #typescript #webdevelopment

  • No alternative text description for this image

Good pattern for strict design systems but it works best in limited scenarios where every style variation (color, border, font, etc.) is defined as a distinct variant. In larger projects, this can get hard to scale since UIs often need small tweaks like extra padding, borders, or backgrounds — that don’t justify creating new variants every time. A more flexible approach is to still define variants but also allow custom classes using utilities like twMerge from Tailwind something like: const Button = ({  children,  variant,  className,  ...rest }: { variant: "primary" | "secondary" | "error" } &   React.ButtonHTMLAttributes<HTMLButtonElement>) => {  const classes = `btn btn-${variant}`;  return (   <button className={twMerge(classes, className)} {...rest}>    {children}   </button>  ); }; I believe this keeps your variants consistent. But also gives flexibility for one-off adjustments without breaking the design system

To view or add a comment, sign in

Explore content categories