Design Converter
Education
Software Development Executive - I
Last updated on Jan 7, 2025
Last updated on Jan 7, 2025
How do you make your React code cleaner and more reusable?
If you’re using React with TypeScript, you’ve probably heard about ComponentProps. This powerful tool helps you manage component properties efficiently and ensures your code stays predictable and type-safe.
In this blog, we’ll break down how to use ComponentProps simply and practically. Stick around to learn tips and examples you can use right away!
React components are powerful building blocks for creating user interfaces. They are essentially JavaScript functions or ES6 classes that accept inputs (called props) and return React elements.
• Props stand for properties and are passed to components as an object, containing data or functions that influence the component’s behavior.
• React components can be defined as function components or class components.
• Developers may design complicated user interfaces by merging simpler elements because components are reusable and composable.
For instance, a function avatar might receive props and render user data dynamically. Here’s an example:
1function Avatar(props: { name: string; imageUrl: string }) { 2 return ( 3 <div className="avatar"> 4 <img src={props.imageUrl} alt={props.name} /> 5 <span>{props.name}</span> 6 </div> 7 ); 8}
Props make components adaptable, enabling child components to render data passed from their parent.
TypeScript enhances React development by providing static typing for props. The ComponentProps utility type is a key feature:
• It extracts and type-checks the props of native elements (e.g., button element, inputs, forms).
• Use cases include defining type ButtonProps or type InputProps for enhanced type safety.
• It’s also useful for extracting props from existing components, even third-party ones. For example:
1import React from "react"; 2 3type ButtonProps = React.ComponentProps<'button'>; 4 5const CustomButton: React.FC<ButtonProps> = (props) => ( 6 <button {...props} className="custom-button" /> 7);
• ComponentProps allows you to extract props from specific components efficiently.
These utilities streamline development, especially when working with all the props from components you don’t control.
Properly typing props ensures clarity and reduces runtime errors. There are several ways to type props in React:
1interface AvatarProps { 2 name: string; 3 imageUrl: string; 4} 5 6const Avatar: React.FC<AvatarProps> = ({ name, imageUrl }) => ( 7 <div className="avatar"> 8 <img src={imageUrl} alt={name} /> 9 <span>{name}</span> 10 </div> 11);
1interface CardProps { 2 children: React.ReactNode; 3} 4 5const Card: React.FC<CardProps> = ({ children }) => ( 6 <div className="card"> 7 {children} 8 </div> 9);
1interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> { 2 label: string; 3} 4 5const TextInput: React.FC<InputProps> = ({ label, ...rest }) => ( 6 <label> 7 {label} 8 <input {...rest} /> 9 </label> 10);
The choice between types and interfaces often depends on context, but interfaces are preferred for public APIs.
HoCs can predefine props for components:
1import React from "react"; 2 3function withDefaultStyle<T extends React.ComponentType<any>>(Component: T) { 4 return (props: React.ComponentProps<T>) => ( 5 <Component {...props} className={`default-style ${props.className || ''}`} /> 6 ); 7}
• Read-only props ensure immutability:
1interface ReadOnlyProps { 2 readonly value: string; 3} 4const ReadOnlyComponent: React.FC<ReadOnlyProps> = ({ value }) => <div>{value}</div>;
• Optional props provide flexibility using ?:
1type ButtonProps = { 2 label?: string; 3};
Export props to allow other components to reuse them:
1export type ButtonProps = React.ComponentProps<'button'>; 2 3export const CustomButton: React.FC<ButtonProps> = (props) => ( 4 <button {...props} className="custom-button" /> 5);
Using the react-select library, you can extract the BaseSelect props:
1import { ComponentProps } from "react"; 2import Select from "react-select"; 3 4type SelectProps = ComponentProps<typeof Select>; 5 6const CustomSelect: React.FC<SelectProps> = (props) => ( 7 <Select {...props} classNamePrefix="custom-select" /> 8);
1import React from "react"; 2 3function withLogger<T>(Component: React.ComponentType<T>) { 4 return (props: T) => { 5 console.log(props); 6 return <Component {...props} />; 7 }; 8}
Functional components use destructuring to retrieve props data:
1function DisplayUser({ name, age }: { name: string; age: number }) { 2 return ( 3 <div> 4 <p>Name: {name}</p> 5 <p>Age: {age}</p> 6 </div> 7 ); 8}
Mastering ComponentProps is crucial for building robust, maintainable React applications. By leveraging TypeScript’s features, such as ComponentProps, interfaces, and utility types, you can:
• Ensure accurate typing for component props.
• Safeguard against runtime errors.
• Simplify integration with third-party libraries and complex UIs.
Continue exploring the evolving React ecosystem and TypeScript’s advanced utilities to stay ahead in building modern web applications.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.