Next.js UI Components — Building a Reusable Component Library
Real projects లో, UI components ni components/ (leda src/components/) folder లో centralize చేయడం best practice — feature-specific components (like AddToCartButton) matrame ఆ feature folder లో ఉంచవచ్చు:
type ButtonProps = {
label: string;
variant?: "primary" | "secondary";
onClick?: () => void;
};
export default function Button({ label, variant = "primary", onClick }: ButtonProps) {
const base = "px-4 py-2 rounded-md font-semibold";
const styles = variant === "primary" ? "bg-green-600 text-white" : "bg-gray-200 text-gray-800";
return (
<button className={`${base} ${styles}`} onClick={onClick}>
{label}
</button>
);
}
variant?: "primary" | "secondary": TypeScript union type — allowed values matrame set చేయవచ్చు, typo-caused bugs runtime కి mundే catch అవుతాయి.
export default function Card({ children }: { children: React.ReactNode }) {
return <div className="rounded-lg shadow-md p-6 bg-white">{children}</div>;
}
children prop వాడితే, Card component లోపల ఏదైనా content pass చేయవచ్చు — chాలా flexible reusable pattern.
Prathi page లో వేర్వేరు button styles (inline CSS/classNames) రాయడం — ఇది chాలా common anti-pattern. ఒక్క reusable Button component build చేసి, variant props ద్వారా customize చేయడం better — design consistency కూడా వస్తుంది.
Build a reusable Badge component that accepts a 'status' prop ('success' | 'error' | 'pending') and renders different background colors.
type BadgeProps = {
status: "success" | "error" | "pending";
};
export default function Badge({ status }: BadgeProps) {
const colors = {
success: "bg-green-500",
error: "bg-red-500",
pending: "bg-yellow-500",
};
return <span className={`px-3 py-1 rounded-full text-white ${colors[status]}`}>{status}</span>;
}
Q components/ folder app/ లోపల pెట్టవచ్చా?
Avunu, kani root level లో (leda src/ వాడితే src/components/) pెట్టడం common convention — దాని valla routing tho confuse అవ్వదు, imports కూడా clean గా ఉంటాయి.
Q Button component Server లేదా Client గా ఉండాలా?
Depends — ఒకవేళ onClick prop వాడుతూ actual interactivity ఉంటే ('use client' అవసరం), కానీ కేవలం styling/display matrame అయితే Server Component గానే ఉండొచ్చు.
Q UI component library (shadcn/ui వంటివి) వాడాలా, స్వంతంగా build చేయాలా?
Beginners కి స్వంతంగా build చేయడం nerchukovడానికి better. Production projects లో, time save చేయడానికి shadcn/ui, Radix UI లాంటి libraries popular గా వాడతారు.